用最簡單的方法實現原生 JS 放大鏡特效

湯清麗發表於2019-12-15
<html lang="en">
<head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
                *{margin:0px;padding:0px;}
                #big{width:200px;height:200px;position:absolute;overflow:hidden;left:480px;top:20px;display:none;}
        </style>
</head>
<body>
        <img src="./1.jpg" width="400" id="small" alt="">
        <div id="big">
                <img src="./1.jpg" alt="">
        </div>
</body>
<script>
        var big = document.getElementById('big');
        var small = document.getElementById('small');
        small.onmousemove = function(e){
                var e = e || event;
                document.title="X:"+e.clientX+"Y:"+e.clientY;
                //獲取對應的大圖的座標
                //將大圖的滾動條的位置調整到小圖的滑鼠座標的4被的位置
                big.scrollLeft = e.clientX*4-80;
                big.scrollTop = e.clientY*4-80;
                //讓對應的大圖顯示
                big.style.display="block";

        }
        small.onmouseout = function(){
                //滑鼠移除之後讓你的大圖隱藏
                big.style.display="none";
        }
</script>
</html>

效果如下:

用最簡單的方法實現原生JS放大鏡特效

相關文章