动态放大镜

68 阅读1分钟

`

1.jpg

Document .left { width: 200px; height: 200px; position: relative; /* margin: 0 auto; */ } .left img { width: 100%; display: block; } .left .plus { width: 100px; height: 100px; background-color: rgba(0, 0, 0, .3); position: absolute; top: 0; left: 0; } .zoom { width: 300px; height: 300px; background-image: url("1.jpg"); } </style>
<script>
    // 放大两倍 放大镜是缩略图的1/4  此值可设置缩略图同放大镜的比例
    var level = 3
    var left = document.querySelector(".left")
    var plus = document.querySelector(".plus")
    var zoom = document.querySelector(".zoom")


    // 获得左边缩略图 宽度和高度
    var leftWidth = left.offsetWidth;
    var leftHeight = left.offsetHeight;
    // console.log(leftWidth);

    // 获得放大镜宽高  这里放大镜的宽高动态给
    // var plusWidth = plus.offsetWidth;
    // var plusHeight = plus.offsetHeight;

    // 获得zoom宽高
    var zoomWidth = zoom.offsetWidth;
    var zoomHeight = zoom.offsetHeight;

    // 计算plus的宽高
    var plusWidth = leftWidth / level
    var plusHeight = leftHeight / level

    // 设置 plus的宽高
    plus.style.width = plusWidth + "px"
    plus.style.height = plusHeight + "px"

    // 根据放大比例设置背景图大小
    zoom.style.backgroundSize = level * 100 + "%"


    var leftOffsleft = left.offsetLeft
    var leftOffstop = left.offsetTop

    // 鼠标移动
    left.onmousemove = function () {
        // console.log(event.pageX); 鼠标距离浏览器可视页面最左边的坐标

        // 鼠标在缩略图上的坐标
        var mouseX = event.pageX - leftOffsleft;
        var mouseY = event.pageY - leftOffstop;
        // console.log(mouseX, mouseY);

        var plusX = mouseX - plusWidth / 2
        var plusY = mouseY - plusHeight / 2

        // 限定遮罩层移动的范围
        if (plusX < 0) {
            plusX = 0
        }
        if (plusX > leftWidth - plusWidth) {
            plusX = leftWidth - plusWidth
        }
        if (plusY < 0) {
            plusY = 0
        }
        if (plusY > leftHeight - plusHeight) {
            plusY = leftHeight - plusHeight
        }

        //遮罩层跟着鼠标走
        plus.style.left = plusX + "px"
        plus.style.top = plusY + "px"

        // zoom.style["background-position"]
        zoom.style["background-position"] =
            -(zoomWidth / plusWidth) * plusX + "px " + -(zoomHeight / plusHeight) * plusY + "px";

    }
</script>
`