手撸一个简单的js放大镜功能

193 阅读1分钟

思路:通过获取鼠标的位置与相对smallbox的偏移量来查看当前大图的位置,注意:鼠标的移动方向相对于图片而言是反向的。

soogif.gif

1.html

<div class="smallbox">
    <div class="bjbox"></div>
</div>
<div class="bigbox"></div>

3.css

.smallbox {
    width: 380px;
    height: 288px;
    position: absolute;
    top: 100px;
    left: 100px;
    background: url(./img/small.png);
}

.bigbox {
    width: 400px;
    height: 400px;
    position: absolute;
    top: 100px;
    right: 100px;
    background: url(./img/big.jpg);
}

.bjbox {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100px;
    height: 100px;
    background: url(./img/bj.png);
}

3.js

 //获取需要的元素 
const smallbox = document.querySelector(".smallbox")
const bjbox = document.querySelector(".bjbox")
const bigbox = document.querySelector(".bigbox")
smallbox.onmouseover = function () {
    document.onmousedown = function () {
        document.onmousemove = function (e) {
            e = e || window.event
            // 获取鼠标在document里面的位置
            let x = e.clientX

            // 得到smallbox在左和上边的偏移量
            let sbl = smallbox.offsetLeft
            let sbt = smallbox.offsetTop

            let y = e.clientY
            // 得到bjbox的宽高
            let bjw = bjbox.offsetWidth
            let bjh = bjbox.offsetHeight

            // 边界的最大最小
            let maxw = smallbox.offsetWidth - bjw
            let maxh = smallbox.offsetHeight - bjh

            //  背景盒子到小盒子的边界的大小
            let l = x - sbl - bjw / 2
            let h = y - sbt - bjh / 2

            // 三目运算  控制背景盒子不允许出小盒子 
            // 如果背景盒子到小盒子边界小于0 就使用0 如果大于最大值就是用 
            // 最小值
            l = l < 0 ? 0 : l;
            // 最大值
            l = l > maxw ? maxw : l

            h = h < 0 ? 0 : h
            h = h > maxh ? maxh : h


            bjbox.style.left = l + "px"
            bjbox.style.top = h + "px"

            // 大盒子的背景定位跟着小盒子的位置的四倍的比例放大(因为图片与鼠标是反向移动,所以用负值)
            bigbox.style.backgroundPosition = `-${l*4}px -${h*4}px`
        }
    }
}
// 背景盒子上面鼠标弹起的时候 停止鼠标移动
bjbox.onmouseup = function () {
    document.onmousemove = !document.onmousemove
}