效果图如下:
HTML代码如下:
<div class="small">
<img src="small2.jpg" alt="" width="400px" height="400px">
<div class="mask"></div>
</div>
<div class="big"><img src="big2.jpg" alt="" width="1200px" height="1200px" class="bigIMG"></div>
CSS代码如下:
<style>
* {
margin: 0;
padding: 0;
}
.small {
position: relative;
left: 20px;
float: left;
width: 400px;
height: 400px;
border: 1px solid black;
overflow: hidden;
cursor: move;
}
.mask {
position: absolute;
top: 0;
left: 0;
display: none;
width: 100px;
height: 100px;
background-color: black;
opacity: .3;
}
.big {
display: none;
position: relative;
top: 0;
top: 0;
float: left;
margin-left: 200px;
width: 600px;
height: 600px;
overflow: hidden;
}
.big img {
/* 因为大图片需要移动,所以必须给定位 */
position: absolute;
left: 0;
top: 0;
}
</style>
JS代码如下:
<script>
var small = document.querySelector('.small');
var mask = document.querySelector('.mask');
var big = document.querySelector('.big');
/* 鼠标移动到小div上时显示mask和大div */
small.addEventListener('mouseover', function() {
mask.style.display = 'block';
big.style.display = 'block';
});
/* 鼠标移出时隐藏mask和大图标 */
small.addEventListener('mouseout', function() {
mask.style.display = 'none';
big.style.display = 'none';
});
small.addEventListener('mousemove', function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
/* 下面代码是为了让mask不超出small */
var maskX = x - mask.offsetWidth / 2;
var maskY = y - mask.offsetHeight / 2
if (maskX <= 0) {
maskX = 0;
} else if (maskX >= small.offsetWidth - mask.offsetWidth) {
maskX = small.offsetWidth - mask.offsetWidth;
}
if (maskY <= 0) {
maskY = 0;
} else if (maskY >= small.offsetHeight - mask.offsetHeight) {
maskY = small.offsetHeight - mask.offsetHeight;
}
/* 上面代码是为了让mask不超出small */
mask.style.left = maskX + 'px'; /* 通过调整固定定位的left和top值改变mask的定位 */
mask.style.top = maskY + 'px';
/* 大图片移动距离 = 遮挡层移动距离(maskX) *大图片移动最大距离(bigMax) / 遮挡层移动最大距离(maskMax) */
var bigIMG = document.querySelector('.bigIMG');
var bigMaxX = bigIMG.offsetWidth - big.offsetWidth;
var maskMaxX = small.offsetWidth - mask.offsetWidth;
var bigMaxY = bigIMG.offsetHeight - big.offsetHeight;
var maskMaxY = small.offsetHeight - mask.offsetHeight;
var bigX = maskX * bigMaxX / maskMaxX;
var bigY = maskY * bigMaxY / maskMaxY;
/* 因为mask移动的正好和大图片移动的相反,所以大图片移动的距离前面应该加上负号 */
bigIMG.style.left = -bigX + 'px';
bigIMG.style.top = -bigY + 'px';
})
</script>
如有疑问欢迎评论区评论