js 图片放大镜

使用js实现图片放大镜的效果。

关于放大镜的基本结构如下图。

实现思路:

1.当鼠标移入小图中时,遮挡层和大图显示层出现。

2.鼠标在遮挡层的中间。

3.遮挡层随着鼠标而移动,不出小图的范围。

4.大图按照比例随着遮挡层移动(遮挡层移动距离/大图移动距离=遮挡层最大移动距离/大图最大移动距离).

5鼠标离开,遮挡层和大图隐藏。

具体实现代码<!DOCTYPE html>

<html>

    <head>
        <meta charset="utf-8" />
        <title></title>
        <style>
            .box {
                margin: 100px;
            }
            
            #small {
                width: 350px;
                height: 449px;
                float: left;
                border: black solid 1px;
                position: relative;
            }
            
            .mask {
                width: 150px;
                height: 150px;
                background-color: rgba(249, 204, 157, 0.6);
                position: absolute;
                display: none;
            }
            
            #big {
                margin-left: 50px;
                float: left;
                width: 500px;
                height: 500px;
                overflow: hidden;
                border: black solid 1px;
                display: none;
            }
        </style>
    </head>

    <body>
<div class="box" id="box"> <div id="small"> <img src="img/small.jpg" alt="" /> <div class="mask"></div> </div> <div id="big"> <img src="img/big.jpg" alt="" /> </div> <div style="clear: both;"></div> </div> <script> //获取元素 var small = document.getElementById("small"); var big = document.getElementById("big"); var mask = small.children[1]; var bigimg = big.children[0]; //鼠标移入 显示遮挡层和大图 small.onmouseover = function() { big.style.display = "block"; small.children[1].style.display = "block"; } //鼠标移动时,遮挡层mask的状态 small.onmousemove = function(e) { //将鼠标控制在遮挡层的中间 var x = e.clientX - mask.offsetWidth / 2; var y = e.clientY - mask.offsetHeight / 2; x = x - 100; y = y - 100; //控制遮挡层的移动范围 x = x < 0 ? 0 : x; y = y < 0 ? 0 : y; x = x > small.offsetWidth - mask.offsetWidth ? small.offsetWidth - mask.offsetWidth : x; y = y > small.offsetHeight - mask.offsetHeight ? small.offsetHeight - mask.offsetHeight : y; mask.style.left = x + "px"; mask.style.top = y + "px"; //控制大图的移动 //大图的移动距离=遮挡层的移动距离*大图的最大移动距离/遮挡层的最大移动距离 // 大图的最大移动距离 var maxX = bigimg.offsetWidth - big.offsetWidth; var maxY = bigimg.offsetHeight - big.offsetHeight; //大图的移动距离 var bigmovex = x * maxX / (small.offsetWidth - mask.offsetWidth); var bigmovey = y * maxY / (small.offsetHeight - mask.offsetHeight); //设置大图移动 bigimg.style.marginLeft = -bigmovex + "px"; bigimg.style.marginTop = -bigmovey + "px"; } //鼠标移出 隐藏遮挡层和大图 small.onmouseout = function() { big.style.display = "none"; small.children[1].style.display = "none"; } </script> </body> </html>

猜你喜欢

转载自www.cnblogs.com/Z7TS/p/9844649.html