狗东同款商品放大镜

315 阅读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{
            width: 300px;
            height: 300px;
            background: red;
            margin: 50px;
            border: 1px solid gray;
        }
        #right{
            width: 500px;
            height: 500px;
            border: 1px solid #ccc;
            background: green;
            position: absolute;
            top: 0;
            left: 300px;
            background-repeat: no-repeat;
        }
    </style>
</head>
<body>
    <div id="left" style="background: url(./img/5a445ba0N2b96e844.jpg) 0 / 100% 100%;"></div>
    <div id="right" style="background: url(./img/5a445ba0N2b96e844.jpg) center; background-size: 200% 200%;"></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>