目标效果:
HTML:
<div class="bigg">
<img src="DSC_1929.jpg" alt="">
<div class="small"></div>
<div class="biggr">
<img src="DSC_1929 copy.jpg" alt="" class="imgg">
</div>
</div>
small是阴影区 biggr是右边的放大区
CSS:
<style>
* {
padding: 0;
margin: 0;
}
.bigg {
position: relative;
width: 500px;
height: 700px;
background-color: red;
margin: 100px auto;
}
.bigg>img {
width: 500px;
height: 700px;
}
.small {
position: absolute;
display: none;
top: 0;
left: 0;
width: 200px;
height: 200px;
background-color: rgba(0, 0, 0, 0.6);
}
.biggr {
position: absolute;
/* display: none; */
top: 0;
left: 550px;
width: 800px;
height: 800px;
overflow: hidden;
}
.biggr .imgg {
position: absolute;
top: 0;
left: 0;
}
</style>
JavaScript:
<script>
window.addEventListener('load', function () {
var bigg = document.querySelector('.bigg');
var small = document.querySelector('.small');
var biggr = document.querySelector('.biggr');
var imgg = biggr.querySelector('.imgg')
//鼠标进入时 相关元素显示
bigg.addEventListener('mouseover', function (e) {
small.style.display = 'block';
biggr.style.display = 'block';
console.log(2);
})
//鼠标离开时 相关元素显示
bigg.addEventListener('mouseout', function () {
small.style.display = 'none';
biggr.style.display = 'none';
})
bigg.addEventListener('mousemove', function (e) {
//获取阴影区的移动距离
var xxori = e.pageX - bigg.offsetLeft - small.offsetWidth / 2;
var yyori = e.pageY - bigg.offsetTop - small.offsetHeight / 2;
//给阴影区的移动距离设置限制,使其不至于超出边界
if(xxori<0){
xxori = 0;
}
else if(xxori>bigg.offsetWidth -small.offsetWidth){
xxori = bigg.offsetWidth -small.offsetWidth
}
if(yyori<0){
yyori = 0;
}
else if(yyori>bigg.offsetHeight -small.offsetHeight){
yyori = bigg.offsetHeight -small.offsetHeight
}
//给阴影区设置移动距离
small.style.top = yyori + 'px';
small.style.left = xxori + 'px';
//给右边大图片设置移动距离
imgg.style.top = -yyori*(imgg.offsetHeight - biggr.offsetHeight)/ (bigg.offsetHeight -small.offsetHeight)+ 'px';
imgg.style.left = -xxori*(imgg.offsetHeight - biggr.offsetHeight)/ (bigg.offsetHeight -small.offsetHeight)+ 'px';
})
})
</script>
值得注意的是,最后 右边大盒子的移动距离采用的是比例的计算方法,且方向相反 即
= -阴影区移动距离*大图片最大移动距离/阴影区最大移动距离