Css

PC端图片放大镜效果

2021-03-09  本文已影响0人  ada_e172

先看效果


录制_2021_03_09_14_29_49_851.gif

鼠标放到图片上,右边会显示鼠标停留处的放大效果。商城之类的网站还是经常会用到的,有兴趣的同学可以看下。如果使用vue或react,可以考虑封装成组件调用,更加方便些。

Html
<div class="ks-image" @mousemove="onMouseOver" id="imgObj">
     <img src='./images/food.jpg' alt="" width="100%"/>
    <span class="ks-imagezoom-lens" id="imgMask"/>
</div>
<div class="ks-overlay ks-imagezoom-viewer ks-overlay-hidden">
    <img src='./images/food.jpg' id='bigImageObj'/>
</div>
Js
onMouseOver(event) {
        const imgObj = document.getElementById("imgObj");
        const imgMask = document.getElementById("imgMask");
        const bigImageObj = document.getElementById("bigImageObj");

        let x = event.clientX - (imgObj.offsetParent.offsetLeft + imgObj.offsetLeft);//减去元素相对于窗口的X轴距离
        let y = event.clientY - (imgObj.offsetParent.offsetTop + imgObj.offsetTop);//减去元素相对于窗口的Y轴距离

        if (x - imgMask.offsetWidth / 2 >= 0 && x + imgMask.offsetWidth / 2 <= imgObj.offsetWidth) {
          imgMask.style.left = (x - imgMask.offsetWidth / 2) + 'px';
          bigImageObj.style.left = -(x - imgMask.offsetWidth / 2) + 'px';
        }

        if (y - imgMask.offsetHeight / 2 >= 0 && y + imgMask.offsetHeight / 2 <= imgObj.offsetHeight) {
          imgMask.style.top = (y - imgMask.offsetHeight / 2) + 'px';
          bigImageObj.style.top = -(y - imgMask.offsetHeight / 2) + 'px';
        }
      }
Css
.ks-image {
        position: relative;
        overflow: hidden;
        width: 358px;
        height: 358px;

        .ks-imagezoom-lens {
            position: absolute;
            display: none;
            background: url("./images/ks-imagezoom-mask.png") repeat scroll 0 0 transparent;
            cursor: move;
            z-index: 1;
            font-size: 0;
            width: 100px;
            height: 100px;
        }

        &:hover {
            .ks-imagezoom-lens {
                display: block;
            }

            & + .ks-imagezoom-viewer {
                display: block;
            }
        }

        & + .ks-imagezoom-viewer {
            display: none;
            position: absolute;
            left: 400px;
            top: 30px;
            width: 358px;
            height: 358px;
            overflow: hidden;
            z-index: 9;

            img {
                width: 800px !important;
                height: 800px !important;
                position: absolute
            }
        }
    }
动动小手,给我点个赞吧.png
上一篇下一篇

猜你喜欢

热点阅读