先看代码,拖到最下面有效果动图展示
结构代码:
<div class="box-2">
<img src="images/易烊千玺min.jpg" alt="">
<div class="mask"></div>
<div class="big">
<img src="images/易烊千玺big.jpg" alt="" class="bigImg">
</div>
</div>
样式代码:
<style>
.box-2 {
position: relative;
width: 466px;
height: 262px;
border: 1px solid rgb(109, 109, 109);
}
.mask {
display: none;
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
background-color: #fede4f;
opacity: .5;
border: 1px solid #ccc;
cursor: move;
}
.big {
display: none;
position: absolute;
top: 0;
left: 470px;
width: 400px;
height: 400px;
background-color: #a50f0f;
z-index: 999;
border: 1px solid #ccc;
overflow: hidden;
}
.big img {
position: absolute;
top: 0;
left: 0;
}
</style>
js代码:
<script>
window.addEventListener('load', function() {
var box2 = this.document.querySelector('.box-2');
var mask = document.querySelector('.mask');
var big = document.querySelector('.big');
box2.addEventListener('mouseover', function() {
mask.style.display = 'block';
big.style.display = 'block';
})
box2.addEventListener('mouseout', function() {
mask.style.display = 'none';
big.style.display = 'none';
})
box2.addEventListener('mousemove', function(e) {
//1、先计算鼠标在盒子内坐标
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
//盒子高度的一半
var maskX = x - mask.offsetWidth / 2;
var maskY = y - mask.offsetHeight / 2;
//如果x坐标小于0,就让他停在0的位置
var maskMaxX = box2.offsetWidth - mask.offsetWidth;
var maskMaxY = box2.offsetHeight - mask.offsetHeight;
if (maskX <= 0) {
maskX = 0;
} else if (maskX >= maskMaxX) {
maskX = maskMaxX;
}
if (maskY <= 0) {
maskY = 0;
} else if (maskY >= maskMaxY) {
maskY = maskMaxY;
}
mask.style.left = maskX + 'px';
mask.style.top = maskY + 'px';
//大图的移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
//大图
var bigImg = document.querySelector('.bigImg');
//大图片最大移动距离
var bigMaxX = bigImg.offsetWidth - big.offsetWidth;
var bigMaxY = bigImg.offsetHeight - big.offsetHeight;
//大图片移动距离
var bigX = maskX * bigMaxX / maskMaxX;
var bigY = maskY * bigMaxY / maskMaxY;
bigImg.style.left = -bigX + 'px';
bigImg.style.top = -bigY + 'px';
})
})
</script>
效果展示: