如下是效果视频:
Document - Google Chrome 2022-03-21 22-50-26
首先我们制作两个容器用于存放原图和放大后的图片
<div class="shop">
<div class="slider"></div>
</div>
<div class="mirror">
<img src="img/xhr.jpeg" alt="">
</div>
然后给它加一些样式 如下:
* {
margin: 0;
padding: 0;
}
.shop {
width: 300px;
height: 500px;
background-color: brown;
background-image: url(img/xhr.jpeg);
background-size: 100% 100%;
border: 1px solid #000;
float: left;
position: relative;
}
.shop .slider {
width: 150px;
height: 150px;
background-color: gold;
opacity: .5;
position: absolute;
display: none;
}
.mirror {
width: 300px;
height: 500px;
overflow: hidden;
border: 1px solid #000;
margin-left: 40px;
float: left;
position: relative;
display: none;
}
img {
width: 600px;
height: 1000px;
position: absolute;
}
然后就是js内容了 我们首先获取所有的元素
var dShop = document.querySelector(".shop");
var dSlider = document.querySelector(".slider");
var dMirror = document.querySelector(".mirror");
var img = document.querySelector("img");
这里我们用 通过css选择器获取元素,返回匹配的元素
然后添加鼠标移入移出的事件
dShop.onmouseenter = function() {
dSlider.style.display = "block";
dMirror.style.display = "block";
}
dShop.onmouseleave = function() {
dSlider.style.display = "none";
dMirror.style.display = "none";
}
然后进行原图与放大图之间的同步 首先是原图的移动距离获取 并且对选中区域进行了范围限制
dShop.onmousemove = function(e) {
var x = e.clientX - this.offsetLeft - 75;
var y = e.clientY - this.offsetTop - 75;
x = (x<0) ? 0 : x;
x = (x>150) ? 150 : x;
y = (y<0) ? 0 : y;
y = (y>350) ? 350 : y;
dSlider.style.left = x + 'px';
dSlider.style.top = y + 'px';
}
然后是同步
dShop.onmousemove = function(e) {
var l1 = dSlider.offsetLeft;
var r1 = dSlider.offsetTop;
var t1 = 300;
var tt1 = 500;
var t2 = 600;
var tt2 = 1000;
var l2 = l1 * t2 / t1 * -1;
var r2 = r1 * tt2 / tt1 * -1;
img.style.left = l2 + 'px';
img.style.top = r2 + 'px';
}
最终就形成啦
|