放大镜效果
用class语法写放大镜效果
如果你经常逛淘宝,你会发现,当点击某件商品进入链接后,鼠标移到商品上,在右边会出现图片放大的效果,这就是放大镜效果,今天给大家分享一下这个放大镜效果。
首先
准备一张图片,布局如下
<div class="zoom">
<div class="small">
<img src="./1.jpg" alt="">
<span></span>
</div>
<div class="large">
<img src="./1.jpg" alt="">
</div>
</div>
样式
<style>
.zoom .small {
width: 400px;
height: 400px;
float: left;
margin: 50px;
position: relative;
}
.zoom .small img{
width: 400px;
height: 400px;
}
.zoom .small span {
position: absolute;
width: 100px;
height: 100px;
left: 0;
top: 0;
background: rgba(194, 172, 172, 0.5);
display: none;
}
.zoom .large{
width: 400px;
height: 400px;
overflow: hidden;
margin: 50px;
position: relative;
float: left;
display: none;
}
.zoom .large img{
position: absolute;
}
</style>
需要注意的是布局是两个盒子,大的隐藏,小的显示
然后就是JS部分
当鼠标移入小盒子,显示透明框和大图片,移动时,大图片也移动
class Glass {
constructor () {
this.small = document.querySelector(".small");
this.span = document.querySelector(".small span");
this.large = document.querySelector(".large");
this.img = document.querySelector(".large img");
this.addEvent();
}
addEvent () {
var _this = this;
this.small.onmouseover = function () {
_this.enter();
}
this.small.onmousemove = function (eve) {
var e = eve || window.event;
_this.move(e);
}
this.small.onmouseleave = function () {
_this.leave();
}
}
enter () {
this.span.style.display = "block";
this.large.style.display = "block";
}
move (e) {
let l = e.clientX - this.span.offsetWidth;
let t = e.clientY - this.span.offsetHeight;
let disW = this.small.offsetWidth - this.span.offsetWidth;
let disH = this.small.offsetHeight - this.span.offsetHeight;
if(l<0)l=0;
if(t<0)t=0;
if (l>disW) l = disW;
if (t>disH) t = disH;
this.span.style.left = l + "px";
this.span.style.top = t + "px";
// 大图片移动
// 获取比例
let x = l/disW;
let y = t/disH;
this.img.style.left = (this.large.offsetWidth - this.img.offsetWidth)*x + "px";
this.img.style.top = (this.large.offsetHeight - this.img.offsetHeight)*y + "px";
}
leave () {
this.span.style.display = "none";
this.large.style.display = "none";
}
}
new Glass();
这里需要注意的是,大图与小图之间的比例,这个比例与移动时大图移动的比例是相同的且方向相反。
其实这里的放大镜的效果的原理是两张一样的图片,一张限制宽高,是小的图片,另一张是大的图片,给人一种放大的感觉
还有最后感谢浏览啦!毕竟我是个新手,欢迎指出错误呀。