jQuery放大镜

这个效果还不错

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{margin: 0;padding: 0}
        .box1{width: 400px;height: 255px;border: 1px solid #ccc;margin:60px;position: relative;}
        .box2{width: 400px;height: 300px;border: 1px solid #ccc;position: absolute;overflow: hidden;top:0;left: 500px;margin: 50px}
        .box2>img{position:absolute;}
        .fu{width: 160px;height: 120px;background:#ffffcc;border: 1px solid #ccc;position: absolute;opacity: 0.5;}
    </style>
</head>
<body>
    <div class="magnifier">
        <div class="box1">
            <div class="fu"></div>
            <img src="http://cdn.attach.qdfuns.com/notes/pics/201708/07/144141buvdo9pxfhfxfxuo.jpg" alt="">
        </div>
        <div class="box2">
            <img src="http://cdn.attach.qdfuns.com/notes/pics/201708/07/144134kfyiyiy14chyyydi.jpg" alt="">
        </div>
    </div>
   <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    <script>
        $(function(){
//初始化
            $(".fu,.box2").hide();
            $(".box1").hover(function(){
                $(".fu,.box2").show();
            },function(){
                $(".fu,.box2").hide();
            });
            $(".box1").mousemove(function (e) {
                //元素距离浏览器的位置
                var ex=e.pageX;
                var ey= e.pageY;
                //获得到box1的偏移量
                var boxx=$(this).offset().left;
                var boxy=$(this).offset().top;
                ////获得到浮窗的宽高
                var fuw=$(".fu").width();
                var fuh=$(".fu").height();
                //获得box的宽高
                var boxw=$(this).width();
                var boxh=$(this).height();
                //获得box2的宽高
                var box2w=$(".box2").width();
                var box2h=$(".box2").height();
                //获得放大的img的宽高
                var imgw=$(".box2>img").width();
                var imgh=$(".box2>img").height();
                //求得偏移量
                var left=ex-boxx-fuw/2;
                var top=ey-boxy-fuh/2;
                //判断边界区域
                if(left<0){
                    left=0;
                }else if(left>(boxw-fuw)){
                    left=boxw-fuw;
                }
                if(top<0){
                    top=0;
                }else if(top>boxh-fuh){
                    top=boxh-fuh;
                }
                //求得比率
                var psx=left/(boxw-fuw);
                var psy=top/(boxh-fuh);
;               $(".fu").css({"left":left,"top":top});
                $(".box2>img").css({"left":-psx*(imgw-box2w),"top":-psy*(imgh-box2h)});
            });
        });
    </script>
</body>
</html>
posted @ 2017-08-16 14:21  终身学习者  阅读(117)  评论(0编辑  收藏  举报