注意将.mask设置成pointer-events: none; 取消它的鼠标事件,否者鼠标移至图片时,会不停的mouseover与mouseout,出现闪动现象
<body>
<div class='container'>
<img class='small' src=".\1.jpg" alt="">
<div class='mask'></div>
<div class='rightView'>
<img class='big' src=".\1.jpg" alt="">
</div>
</div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
.container {
position: relative;
top: 100px;
left: 200px;
width: 400px;
height: 400px;
border: 1px solid black;
}
.container .mask {
background: rgba(50, 153, 248, 0.4);
position: absolute;
display: none;
cursor: move;
pointer-events: none;
}
.container .small {
display: block;
height: 400px;
margin: 0 auto;
}
.container .rightView {
display: none;
position: absolute;
left: 410px;
top: 0;
height: 400px;
overflow: hidden;
}
.container .rightView .big {
position: absolute;
}
</style>
<script>
var container = document.getElementsByClassName('container')[0]
var rightView = document.getElementsByClassName('rightView')[0]
var mask = document.getElementsByClassName('mask')[0]
var bigImg = document.getElementsByClassName('big')[0]
var smallImg = document.getElementsByClassName('small')[0]
// 鼠标移至图片时,mask与rightView显示
smallImg.addEventListener('mouseover', function () {
rightView.style.display = 'block'
mask.style.display = 'block'
})
// 鼠标移出图片时,mask与rightView消失
smallImg.addEventListener('mouseout', function () {
rightView.style.display = 'none'
mask.style.display = 'none'
})
// 鼠标在图片上移动时的代码
smallImg.addEventListener('mousemove', function (e) {
e = e || window.event
//设置rightView的宽度和mask的长宽
rightView.style.width = smallImg.offsetWidth
mask.style.width = smallImg.offsetWidth * 2 / 5
mask.style.height = smallImg.offsetHeight * 2 / 5
//smallImg的高度在css中规定,对于不同的图片,左右会有一个空隙,mouseX的值要减去这个空隙值
mouseX = e.pageX - container.offsetLeft - smallImg.offsetLeft - mask.offsetWidth / 2
mouseY = e.pageY - container.offsetTop - mask.offsetHeight / 2
//鼠标移至smallImg的边缘时,mask应该保持在smallImg之内
if (mouseX <= 0) {
mouseX = 0
}
if (mouseY <= 0) {
mouseY = 0
}
let maxScopeX = smallImg.offsetWidth - mask.offsetWidth
let maxScopeY = smallImg.offsetHeight - mask.offsetHeight
if (mouseX >= maxScopeX) {
mouseX = maxScopeX
}
if (mouseY >= maxScopeY) {
mouseY = maxScopeY
}
//mask是相对container定位的,要想不出smallImg,就要加上空隙的值
mask.style.left = mouseX + smallImg.offsetLeft + 'px'
mask.style.top = mouseY + 'px'
//mask相对smallImg的位置等同于rightView相对于bigImg的位置,计算他们的比列就能使mask与rightView的显示区域相同
imgProportion = (bigImg.offsetHeight - rightView.offsetHeight) / (smallImg.offsetHeight - mask.offsetHeight)
bigImg.style.left = -imgProportion * mouseX + 'px'
bigImg.style.top = -imgProportion * mouseY + 'px'
})
</script>