商品放大镜

鼠标事件

移入:移入到left元素上,mask和right显示
    遮罩跟随:鼠标到哪里我的遮罩就运动到哪里

宽高问题

遮罩的大小/小图的大小=大盒子的大小/大图的大小

样式

#box{
width: 200px;
height: 200px;
border: 3px solid black;
position: relative;
}
#left{
width: 200px;
height: 200px;
border: 3px solid red;
position: absolute;
/* 让box和left重合 */
left: -3px;
top: -3px;
background: url(./img/1.jpg);
background-size: 200px 200px;
}
#right{
width: 200px;
height: 200px;
border: 3px solid blue;
position: absolute;
left: 220px;
top: -3px;
background: url(./img/1.jpg) no-repeat;
background-size: 400px 400px;
display: none;
}
/* mask的大小需要遵循一定的比例
遮罩的大小/小图的大小=大盒子的大小/大图的大小
*/
#mask{
width: 100px;
height: 100px;
background-color: rgba(255, 255, 0, 0.3);
display: none;
position: absolute;
}

 

结构

<body>
<div id="box">
<div id="left">
<div id="mask"></div>
</div>
<div id="right"></div>
</div>
</body>

 


js代码

/*
移入:移入到left元素上,mask和right显示
遮罩跟随:鼠标到哪里我的遮罩就运动到哪里
*/
var oBox=document.querySelector('#box')
var oLeft=oBox.children[0]
var oRight=oBox.children[1]
var oMask=oLeft.children[0]

//移入移出的效果
oLeft.onmouseover=function(){
oMask.style.display='block'
oRight.style.display='block'
}
oLeft.onmouseout=function(){
oMask.style.display='none'
oRight.style.display='none'
}

//遮罩跟随:鼠标到哪里我的遮罩就运动到哪里(联想到天使飞,鼠标到哪儿,天使就飞到哪儿)
oLeft.onmousemove=function(e){
let l=e.clientX-oBox.offsetLeft
let t=e.clientY-oBox.offsetTop

let ll=l-oMask.offsetWidth/2
let tt=t-oMask.offsetHeight/2


if(ll<0){
ll=0
}
if(ll>=oLeft.clientWidth-oMask.offsetWidth){
ll=oLeft.clientWidth-oMask.offsetWidth
}

if(tt<0){
tt=0
}
if(tt>=oLeft.clientHeight-oMask.offsetHeight){
tt=oLeft.clientHeight-oMask.offsetHeight
}


// ll和tt分别是遮罩层的运动的left和top,大图运动的应该是2倍 ll和tt
oMask.style.left=ll+'px'
oMask.style.top=tt+'px'

oRight.style.backgroundPositionX=-2*ll+'px'
oRight.style.backgroundPositionY=-2*tt+'px'
}

//x=200*200/400=100
posted @ 2022-11-19 17:13  Orgy  阅读(32)  评论(0)    收藏  举报