效果图:
代码实现:
HTML.
<!-- 原图盒子 -->
<div class="small-box">
<!-- 放大镜-->
<div class="float-box"> <!-- 蒙层 --></div>
<img src="PICTURE/d.jpg" class="small-img">
<!-- 大图显示-->
<div class="big-box">
<img class="big-img" src="PICTURE/d.jpg">
</div>
</div>
CSS.
/*原图盒子*/
.small-box {
position: relative; /*原图盒子相对定位(其他都绝对)*/
width:400px;
height:400px;
}
/*原图*/
.small-img {
width: 100%;
height: 100%;
}
/*滑块*/
.float-box {
display: none;
width: 160px;
height: 160px;
position: absolute; /*相对父级偏移*/
background: #9a9a9a;
opacity: 0.5;
pointer-events: none;
}
/*放大镜盒子*/
.big-box{
display: none;
position: absolute;
top:0;
left: 450px;
width: 400px;
height: 400px;
overflow: hidden;
pointer-events: none; /*去掉鼠标事件*/
}
/*放大镜中图片*/
.big-box img{
position: absolute;
width:250%; /*此比例为滑块宽/原图宽*/
height:250%;
}
JS.
var objSmallBox = document.querySelector(".small-box")
var objFloatBox = document.querySelector(".float-box")
var smallImg = document.querySelector(".small-img")
var objBigBox = document.querySelector(".big-box")
var objBigBoxImage = document.querySelector(".big-img")
//移入事件(显示蒙层和放大镜)
smallImg.addEventListener("mouseover",function(){
objFloatBox.style.display="block"
objBigBox.style.display="block"
}
)
//移出事件(关闭蒙层和放大镜)
smallImg.addEventListener("mouseout",function(){
objFloatBox.style.display="none"
objBigBox.style.display="none"
})
//移动事件
smallImg.addEventListener("mousemove",function(e){
var rect=smallImg.getBoundingClientRect() //返回此元素相对于视窗偏移信息
var left=e.clientX-rect.left-80 //滑块相对大盒偏移(左/上边界)=鼠标坐标-元素到视窗偏移-(自身边长/2)
var top=e.clientY-rect.top-80 //元素上边到视窗上边的距
if(left<0){
left=0
}
else if(left>(objSmallBox.offsetWidth-objFloatBox.offsetWidth)){ //滑块偏移量>父盒子宽-滑块宽(即出界)
left=objSmallBox.offsetWidth-objFloatBox.offsetWidth
}
if(top<0){
top=0
}
else if(top>(objSmallBox.offsetHeight-objFloatBox.offsetHeight)){
top=objSmallBox.offsetHeight-objFloatBox.offsetHeight
}
//放大镜位置
objFloatBox.style.left=left+"px" //相对父盒子偏移
objFloatBox.style.top=top+"px"
//计算百分比
var percentX=left/(objSmallBox.offsetWidth-objFloatBox.offsetWidth) //偏移量/偏移范围
var percentY=top/(objSmallBox.offsetHeight-objFloatBox.offsetHeight)
//显示图片相对位置
objBigBoxImage.style.left=-percentX*(objBigBoxImage.offsetWidth-objBigBox.offsetWidth)+"px"//反向移动
objBigBoxImage.style.top=-percentY*(objBigBoxImage.offsetHeight-objBigBox.offsetHeight)+"px"
})
若有可以优化代码的地方,希望补充指正!