JS实现简单放大镜效果

预览图

在这里插入图片描述

首先我们要在body里面写我们需要的标签,用img引用外部图片

<body>
     <div class="box">
          <img src="img/cy.jpg" alt="" width="100%">
          <div class="clicr">
              <img src="img/cy.jpg" alt="" >
          </div> 
     </div>
</body>

然后我们就要对样式进行设置,这里主要使用link链接

.box{
    
    
    width: 1000px;
    min-height: 200px;
    position: relative;<!-- 子绝父相-->
}
.clicr{
    
    <!-- 这个是放大镜的样式-->
    width:200px;
    height: 200px;
    border-radius: 50%;
    position: absolute;
    box-shadow: 1px 1px 10px 1px gray;
    left: 0;
    top: 0;
    overflow: hidden;<!-- 溢出隐藏-->
    opacity: 0 ;<!-- 这里设置透明度后面会用到-->
}
.clicr img{
    
    
    position: absolute;
    left: 0;
    top: 0;
}

接下来我们就要js进行编写,这里直接用内部式(用外部引入也可以),用内部式就要在body后加一个script标签把js代码写在里面。我们先要获取到这两个div 和放大镜里的图片,这里我用的是获取class的方法,也可以用获取id的方法,当然要把上面的class改为id命名

 const box = document.querySelector(".box");
 const clicr = document.querySelector(".clicr");
 const bigImg = document.querySelector(".clicr img");

接下来我们就要写放大镜效果,然后让放大镜随着鼠标的移动而移动

box.addEventListener('mousemove',function(e){
    
    
        let x = e.clientX;//获取鼠标x轴偏移量,是相对于body的
        let l = box.offsetLeft;//box相对于body的偏移量
        let clicrLeft = x - l - clicr.offsetWidth/2;//让鼠标在放大镜中间
        if(clicrLeft <= 0) clicrLeft = 0;//边缘检测
        let maxLeft = box.offsetWidth - clicr.offsetWidth;
        if(clicrLeft >= maxLeft) clicrLeft = maxLeft;//边缘检测
        clicr.style.left = clicrLeft + "px";//放大镜相对于box的偏移量
        let bigImgLeft = (clicrLeft + clicr.offsetWidth/4)/box.offsetWidth*bigImg.offsetWidth - clicr.offsetWidth/4
        /*这里用的是鼠标距离小图(box)left的偏移量比上小图宽度
        等于鼠标距离大图left的偏移量比上大图宽度,然后还要减去放大镜宽度的一半,
        根据这个公式可以求出bigImgLeft ,
        这里(clicr.offsetWidth/4 )应该宽度的一半,但是我试了,填4效果感觉更好*/
        bigImg.style.left=  -bigImgLeft + "px";
        //这里y要加上负号,不加不会报错,但是放大镜里的图片示不能正常显示。
        ......
        //下面还有纵向的,只是把上面的left改为top 和 width 改为 height就行了
    })

最后只要让鼠标移入时放大镜显示,移除时隐藏就行了

    box.addEventListener('mouseover',function(){
    
    
       clicr.style.opacity="1";
    });
    box.addEventListener('mouseout',function(){
    
    
        clicr.style.opacity="0";
    });
    //这里就用到了透明度,鼠标移出时不显示放大镜,只要鼠标移入就显示放大镜。

这样一个简单的放大镜效果就做完了

猜你喜欢

转载自blog.csdn.net/Inory_ye/article/details/112585785