放大镜

作者: 甘草子XS | 来源:发表于2016-11-14 12:12 被阅读0次

    布局

    html代码

    <div id="box">
        <div id="smallImg">
            <div id="shank"></div>
            <img id="small" src="img/1.jpg"/>
        </div>
        <div id="bigImg">
            <img id="big" src="img/1.jpg"/>
        </div>
    </div>
    

    css代码

    *{
        margin: 0;
        padding: 0;
    }
    #box{
        width: 1000px;
        margin: 100px auto;
    }
    #smallImg{
        width: 300px;
        height: 300px;
        float: left;
        position: relative;
    }
    #small{
        width: 100%;
        height: 100%;
    }
    #shank{
        width: 150px;
        height: 150px;
        background: #000;
        opacity: 0.4;
        position: absolute;
        top: 0;
        left: 0;
        cursor: move;
        display: none;
    }
    #bigImg{
        width: 400px;
        height: 400px;
        overflow: hidden;
        margin-left: 20px;
        float: left;
        position: relative;
    }
    #big{
        width: 600px;
        height: 600px;
        display: none;
        position: absolute;
        top: 0;
        left: 0;
    }
    

    接下来js代码

    var oSmallImg = document.getElementById("smallImg")
    var oShank = document.getElementById("shank");
    var oBig = document.getElementById("big");
    var oBigImg = document.getElementById("bigImg");
    oSmallImg.onmouseover = function(){
        oShank.style.display = 'block';
        oBig.style.display = 'block';
    }
    oSmallImg.onmouseout = function(){
        oShank.style.display = 'none';
        oBig.style.display = 'none';
    }
    oShank.onmousemove = function( ev ){
        ev = ev || event;
        var sL = ev.clientX - oSmallImg.offsetLeft - oShank.offsetWidth/2;
        var sT = ev.clientY - oSmallImg.offsetTop - oShank.offsetHeight/2;
        var w = oSmallImg.offsetWidth - oShank.offsetWidth;
        var h = oSmallImg.offsetHeight - oShank.offsetHeight;
        var bW = oBig.offsetWidth;
        var bH = oBig.offsetHeight;
        //设置百分比
        var preX = sL/w;
        var preY = sT/h;
        if( sL > w ){
            sL = w;
        }else if( sL < 0 ){
            sL = 0;
        };
        if( sT > h ){
            sT = h;
        }else if( sT < 0 ){
            sT = 0;
        };
        oShank.style.left = sL + 'px';
        oShank.style.top = sT + 'px';
        oBig.style.left = -preX*( bW - oBigImg.offsetWidth ) + 'px';
        oBig.style.top = -preY*( bH - oBigImg.offsetHeight ) + 'px';
    };
    

    效果图

    放大镜.jpg

    相关文章

      网友评论

          本文标题:放大镜

          本文链接:https://www.haomeiwen.com/subject/gxshpttx.html