图片的放大镜效果

昨天看一篇博文的时候,说到了这个效果,于是自己想试着写一个,没有使用插件,

基本的想法就是,左边是小图,右边对应大图,鼠标进去小图范围之后,获取他的坐标(x,y)然后计算

x/小图的宽度*大图得宽度/2

y/小图的高度*大图得高度/2

计算出来的两个结果即为大图得左右偏移距离

/2是为了让右边区域不会出现空白。

经过测试,ie7以上以及主流浏览器都可以用,代码如下:

<div class="wrap">
    <div class="small">
        <img src="1s.jpg">
        <div class="tool" id="tool"></div>
    </div>
    <div class="big"><img src="1.jpg"></div>
</div>
.wrap{overflow:hidden;margin:50px auto;}
.small{position:relative;float:left;width:214px;height:328px;}
  .tool{width:100px;height:100px;position:absolute;top:50px;left:100px;background:rgba(255,255,255,0.5);}
  .big{float:left;margin:0 40px;width:330px;overflow:hidden;height:328px;display:none;position:relative;}
.big img{position:absolute;width:650px;height:960px;}

主要的JS代码如下:

//不加蒙版放大镜
        $('.small').mousemove(function(e) {
            $(this).siblings('.big').show();
            //var e = event || window.event;
            var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;//滚动条距离屏幕左边的宽度
            var scrollY = document.documentElement.scrollTop || document.body.scrollTop;//滚动条距离屏幕上面的高度
            //e.pageX相对于文档左边的高度
            //e.pageY相对于文档上面的高度

            //e.clientX相对于屏幕左边的高度
            //e.clientY相对于屏幕上面的高度
            var xx = e.pageX || e.clientX + scrollX;//相对于文档左边的宽度
            var yy = e.pageY || e.clientY + scrollY;//相对于文档上面的高度
            //.offset().top元素相对于文档上面的位置
            //.offset().left元素相对于文档左面的位置
            var y=yy-$(this).offset().top;//鼠标相对于元素的x,y坐标
            var x=xx-$(this).offset().left;
            var width=$(this).width();
            var lwidth=$(this).siblings('.big').find('img').width();
            //按照大图与小图的比例来进行移动的
            var left=x/width*lwidth/2;
            var height=$(this).height();
            var lheight=$(this).siblings('.big').find('img').height();
            var top=y/height*lheight/2;
            $(this).siblings('.big').find('img').css({left:-left,top:-top});
            //console.log(x + '---' + y);
            //不加蒙版放大镜结束
            //蒙版跟着动
            var twidth=$(this).find('.tool').width();
            var theight=$(this).find('.tool').height();
            var tleft=x-twidth/2;
            var ttop=y-theight/2;
            if(tleft<0){
                tleft=0;
            }
            if(tleft>width-twidth){
                tleft=width-twidth;
            }
            if(ttop<0){
                ttop=0
            }
            if(ttop>height-theight){
                ttop=height-theight;
            }
            $(this).find('.tool').css({left:tleft,top:ttop});
        });

效果如下:

原文地址:https://www.cnblogs.com/zhaixr/p/7017525.html