代码小白的学习-放大镜特效

273 阅读1分钟
<!DOCTYPE html>
  <html lang="en">

    <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
    #left {
        height: 250px;
        width: 500px;
        background: url(./mao.jpg) no-repeat 0/100% 100%;
        border: 1px solid rgb(105, 105, 105);
    }

    #right {
        height: 500px;
        width: 700px;
        background: url(./mao.jpg) no-repeat 0 /200% 200%;
        position: absolute;
    }
</style>
 </head>

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

<script>
    function $(str) {
        return document.querySelector(str)
    }

    window.onload = function () {
        let l = $('#left').offsetLeft + $('#left').offsetWidth
        let t = $('#left').offsetTop
        $('#right').style.left = l + 'px'
        $('#right').style.top = t + 'px'

        $('#left').onmouseenter = () => {
            $('#right').style.display = 'block'
        }
        $('#left').onmouseleave = () => {
            $('#right').style.display = 'none'
        }
        $('#left').onmousemove = (e) => {
            let x = e.pageX - $('#left').offsetLeft
            let y = e.pageY - $('#left').offsetTop

            x = x / $('#left').offsetWidth
            y = y / $('#left').offsetHeight

            x = (x * 100).toFixed(4) + '%'
            y = (y * 100).toFixed(4) + '%'

            $('#right').style['background-position-x'] = x
            $('#right').style['background-position-y'] = y
        }
    }
</script>
 </body>

</html>