放大镜案例
<style>
.smallBox{
width:400px;
height:300px;
float:left;
margin:50px;
position:relative;
}
.smallBox img{
width:400px;
height:300px;
}
.bigBox{
width:400px;
height:300px;
float:left;
position:relative;
display:none;
overflow: hidden;
}
.bigBox img{
position:absolute;
width:1200px;
height:900px;
}
.smallBox span{
position:absolute;
top:0;
left:0;
background:rgba(100,10,20,0.3);
z-index:2;
display: none;
}
</style>
<body>
<div class="smallBox">
<img src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3267400455,1770908768&fm=26&gp=0.jpg" alt="">
<span></span>
</div>
<div class="bigBox">
<img src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3267400455,1770908768&fm=26&gp=0.jpg" alt="">
</div>
<script>
class Magnifier{
constructor(){
this.sbox = document.querySelector(".smallBox")
this.bbox = document.querySelector(".bigBox")
this.span= document.querySelector(".smallBox span")
this.bimg= document.querySelector(".bigBox img")
this.bandEvent()
}
bandEvent(e){
var that = this
this.sbox.onmouseenter = function(){
that.enter()
}
this.sbox.onmouseleave = function(){
that.leave()
}
this.sbox.onmousemove = function(){
that.move(e)
}
}
init(){
this.span.style.width = this.sbox.offsetWidth / (this.bimg.offsetWidth / this.sbox.offsetWidth) + "px"
this.span.style.height = this.sbox.offsetHeight / (this.bimg.offsetHeight / this.sbox.offsetHeight) + "px"
}
enter(){
this.span.style.display = "block"
this.bbox.style.display = "block"
this.init()
}
leave(){
this.span.style.display = "none"
this.bbox.style.display = "none"
}
move(e){
var e = e || window.event
var left = e.clientX - this.sbox.offsetLeft - this.span.offsetWidth / 2
var top = e.clientY - this.sbox.offsetTop - this.span.offsetHeight / 2
if(left <= 0) left = 0
if(top <= 0) top = 0
if(left >= this.sbox.offsetWidth - this.span.offsetWidth) left = this.sbox.offsetWidth - this.span.offsetWidth
if(top >= this.sbox.offsetHeight - this.span.offsetHeight) top = this.sbox.offsetHeight - this.span.offsetHeight
this.span.style.left = left + "px"
this.span.style.top = top + "px"
var x = left / (this.sbox.offsetWidth - this.span.offsetWidth)
var y = top / (this.sbox.offsetHeight - this.span.offsetHeight)
this.bimg.style.left = (this.bbox.offsetWidth - this.bimg.offsetWidth) * x + "px"
this.bimg.style.top = (this.bbox.offsetHeight - this.bimg.offsetHeight) * y + "px"
console.log(x,y)
}
}
new Magnifier()
</script>
</body>