js实现购物网站放大镜功能

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了js实现购物网站放大镜功能脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

本文实例为大家分享了js实现购物网站放大镜功能的具体代码,供大家参考,具体内容如下

首先看效果图:

先是布局,左边一个小图框,包含一个鼠标移动框,右边一个放大框。

<div class="box">
        <div class="small">
            <img src="small3.jpg" alt="">
            <div class="move"></div>
        </div>
        <div class="Big">
            <img src="big3.jpg" alt="">
        </div>
</div>

写一下css

.small{
    posITion: relative;
    float: left;
    width: 450px;
    height: 450px;
    border:1px solid #000;
}
.small .move{
    position: absolute;
    top:0;
    width: 300px;
    height: 300px;
    background-color: rgba(0,0,0,0.4);
    cursor:move;
    display: none;
}
.big{
    position: relative;
    float: left;
    width: 540px;
    height: 540px;
    margin-left: 20px;
    overflow: hidden;
    border:1px solid #000;
    display: none;
}
.big img{
    position: absolute;
    top:0;
    left: 0;
}

js部分:

VAR box=document.getElementsByclassname('box')[0],small=box.getElementsByClassName('small')[0],move=small.getElementsByClassName('move')[0],smallImg=small.getelementsbytagname('img')[0],big=box.getElementsByClassName('big')[0],bigImg=big.getElementsByTagName('img')[0];
    //首先把需要的元素都获取出来
    small.onmouseover=function(){
        move.style.display='block';
        big.style.display="block";
    };
    small.onmouseout=function(){
        move.style.display='none';
        big.style.display="none";
    };
    small.onmouSEMove=function(e){
        e=e||window.event;//兼容性考虑
        var x=e.clientX-smallImg.getBoundingClientRect().left-move.offsetWidth/2;
        var y=e.clientY-smallImg.getBoundingClientRect().top-move.offsetHeight/2;
        if(x<0){
            x=0;
        }
        if(x>smallImg.offsetWidth-move.offsetWidth){
            x=smallImg.offsetWidth-move.offsetWidth;
        }
        if(y<0){
            y=0;
        }
        if(y>smallImg.offsetHeight-move.offsetHeight){
            y=smallImg.offsetHeight-move.offsetHeight;
        }
        move.style.left=x+"px";
        move.style.top=y+"px";
        //实现左边move块跟随鼠标移动的代码
        var scale=bigImg.offsetWidth/smallImg.offsetWidth;
        //按照比例放大
        bigImg.style.left='-'+x*scale+'px';
        //因为图片是需要左移和上移的所以要加负号
        bigImg.style.top='-'+y*scale+'px';
    }

放大镜效果就实现啦!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的js实现购物网站放大镜功能全部内容,希望文章能够帮你解决js实现购物网站放大镜功能所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。