注:请按比例设置宽高,以确保放大的部位准确
<style>
.left {
width: 300px;
height: 400px;
float: left;
position: relative;
}
.right {
width: 300px;
height: 300px;
background-color: red;
float: left;
margin-left: 50px;
overflow: hidden;
position: relative;
}
.leftImg {
width: 300px;
height: 300px;
}
.st {
width: 40px;
height: 40px;
margin: 5px;
}
.right img {
width: 900px;
height: 900px;
position: absolute;
}
.show {
display: block;
}
.a {
width: 100px;
height: 100px;
background-color: rgba(0, 0, 0, .5);
position: absolute;
top: 0;
left: 0;
display: none;
}
</style>
<div class="box">
<div class="left">
<div class="aaa">
<img src="1.jpg" alt="" class="leftImg">
<div class="a"></div>
</div>
<img src="1.jpg" alt="" class="st">
<img src="2.jpg" alt="" class="st">
<img src="3.jpg" alt="" class="st">
<img src="4.jpg" alt="" class="st">
</div>
<div class="right">
<img src="1.jpg" alt="" id="bigImg">
</div>
</div>
<script>
var arr = ['1.jpg', '2.jpg', '3.jpg', '4.jpg'];
var sImgs = document.querySelectorAll('.st');
var leftImg = document.querySelector('.leftImg');
var aaa = document.querySelector('.aaa');
var a = document.querySelector('.a');
var right = document.querySelector('.right');
sImgs.forEach(function (val, i) {
val.onclick = function () {
leftImg.src = arr[i]
bigImg.src = arr[i]
}
})
aaa.onmouseenter = function () {
a.style.display = 'block'
}
aaa.onmouseleave = function () {
a.style.display = 'none'
}
aaa.onmousemove = function (e) {
e = e || window.event;
var maxW = leftImg.clientWidth - a.offsetWidth;
var maxH = leftImg.clientHeight - a.offsetHeight;
var x = e.pageX - a.offsetWidth / 2;
var y = e.pageY - a.offsetHeight / 2;
if (x < 0) {
x = 0
}
if (y < 0) {
y = 0
}
if (x > maxW) {
x = maxW
}
if (y > maxH) {
y = maxH
}
a.style.left = x + 'px';
a.style.top = y + 'px';
var scale = (bigImg.offsetWidth - right.offsetWidth) / maxW;
bigImg.style.left = -scale * x + 'px';
bigImg.style.top = -scale * y + 'px';
}
</script>