html代码
<body>
<div class="box" id="box">
<div class="small">
<img src="images/small.png" width="350" alt=""/>
<div class="mask"></div>
</div>
<div class="big">
<img src="images/big.jpg" width="800" alt=""/>
</div>
</div>
</body>
css代码
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big {
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.mask {
width: 175px;
height: 175px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.small {
position: relative;
}
</style>
js代码
<script>
var box = my$("box")
var small = box.children[0]
var big = box.children[1]
var mask = small.children[1]
var bigImg = big.children[0]
box.onmouseover = function () {
mask.style.display = "block"
big.style.display = "block"
}
box.onmouseout = function () {
mask.style.display = "none"
big.style.display = "none"
}
//鼠标移动事件
small.onmousemove = function (e) {
var x = e.clientX - mask.offsetWidth / 2
var y = e.clientY - mask.offsetHeight / 2
x = x - 100
y = y - 100
console.log(x)
x = x < 0 ? 0 : x
y = y < 0 ? 0 : y
x = x > small.offsetWidth - mask.offsetWidth ? small.offsetWidth - mask.offsetWidth : x
y = y > small.offsetHeight - mask.offsetHeight ? small.offsetHeight - mask.offsetHeight : y
mask.style.left = x + "px"
mask.style.top = y + "px"
//遮挡层的移动距离/大图的移动距离=遮挡层的最大移动距离/大图的最大移动距离
//大图的横向最大移动距离
var bx = bigImg.offsetWidth - big.offsetWidth
//大图的纵向最大移动距离
var by = bigImg.offsetHeight - big.offsetHeight
//大图的移动距离
var bigImgMoveX = x*bx/(small.offsetWidth - mask.offsetWidth)
var bigImgMoveY = y*by/(small.offsetHeight - mask.offsetHeight)
//改变的是大图的margin值
bigImg.style.marginLeft = -bigImgMoveX + "px"
bigImg.style.marginTop = -bigImgMoveY + "px"
}
</script>