CSS样式
* {
margin: 0;
padding: 0;
}
.left {
width: 300px;
height: 300px;
position: relative;
float: left;
}
.left img {
width: 100%;
height: 100%;
display: block;
position: absolute;
}
.box {
width: 100px;
height: 100px;
background: rgba(0, 0, 0, 0.5);
position: absolute;
left: 0;
top: 0;
}
.right {
width: 300px;
height: 300px;
position: relative;
float: left;
overflow: hidden;
}
.right img {
width: 600px;
height: 600px;
position: absolute;
}
.start {
position: absolute;
left: 10px;
top: 300px;
}
.close {
position: absolute;
left: 100px;
top: 300px;
}
div布局
<div class="left">
<img src="./b1.jpg" alt="" class="left_img">
<p class="box">
</p>
</div>
<div class="right">
<img src="./b1.jpg" alt="" class="right_img">
</div>
<button class="start">开启放大</button>
<button class="close">关闭放大</button>
js代码
let left = document.querySelector('.left');
let right = document.querySelector('.right');
let box = document.querySelector('.box');
let left_img = document.querySelector('.left_img');
let right_img = document.querySelector('.right_img');
let start = document.querySelector('.start');
let close = document.querySelector('.close');
let move = function (e) {
let x = e.pageX - left.offsetLeft - box.offsetWidth / 2;
let y = e.pageY - left.offsetTop - box.offsetHeight / 2;
if (x < 0) {
x = 0
}
if (y < 0) {
y = 0
}
if (x > left.offsetWidth - box.offsetWidth) {
x = left.offsetWidth - box.offsetWidth
}
if (y > left.offsetHeight - box.offsetHeight) {
y = left.offsetHeight - box.offsetHeight
}
box.style.left = x + 'px';
box.style.top = y + 'px';
right_img.style.left = -(1.32 * x) + 'px';
right_img.style.top = -(1.32 * y) + 'px';
close.addEventListener('click', function () {
left.removeEventListener('mousemove', move)
})
start.addEventListener('click', function () {
left.addEventListener('mousemove', move)
})
}
left.addEventListener('mousemove', move)