这是徐超胜的前端开发博客

放大镜查看大图代码

看到园内有人用CSS属性clip:rect()实现了放大镜查看图片的效果,于是我也痒痒的想学一个。本想也用rect来实现的,没想到,rect没用上就实现了效果,然后绞尽脑汁想方设法要用一下rect,最后也确实用上了。直接上吧!

<div class="originImage">
     <div class="rectArea"></div>
  </div>
  <div class="rectedImage">
      <div class="img"></div> 
  </div>
.originImage{
        width:322px;
        height:284px;
        float:left;
        background:url('demo.png');
        position:relative;
    }
    .rectedImage{
        /* width:322px;
                height:284px; */
        /* border:1px solid #F27B04; */
        float:left;
        margin-left:10px;
        position:relative;
    }
    .rectArea{
       width:80px;
       height:80px;
       border-radius:80px;
       background:#000;
       opacity:0.5;
       position:absolute;
       cursor:move;
    }
    .img{
       width:80px;
       height:80px;
       border-radius:80px;
       position:absolute;
       border:3px solid #F27B04;
       background:url('demo.png') no-repeat; 
       position:absolute;
    }
    .mask{
       width:80px;
       height:80px;
       border-radius:80px;
       position:absolute;
       border:16px solid #fff;
    }
var originImage = document.getElementsByClassName("originImage")[0];//原图div
      var rectArea = document.getElementsByClassName("rectArea")[0];//选区div
      var img = document.querySelectorAll('.img')[0];//选择结果的div
      rectArea.onmousedown = function(){
         this.id="couldMove"
      }
      rectArea.onmouseup = function(){
         this.id="couldnotMove"
      }
      rectArea.onmousemove = function(e){
         if(this.id=="couldMove"){
            var left = e.pageX-originImage.offsetLeft;
            var top = e.pageY-originImage.offsetTop;
            this.style.left = left-40+"px";
            this.style.top = top-40+"px";
            if(left >= 282){
               this.style.left = "242px";
            }
            if(left<=40){
               this.style.left = "0px";
            }
            if(top >= 244){
               this.style.top = "204px";
            }
            if(top<=40){
               this.style.top = "0px";
            }
         }
         var offX = rectArea.offsetLeft;
         var offY = rectArea.offsetTop;
         
         img.style.backgroundPosition = -offX+"px "+(-offY)+"px";
  
      }

你看到这里也许有点失望了,就这么点东西,根本不够你学习的,呵呵。效果图如下:

有两个地方是有待加强的:1.选择区应该可以缩大放小。2.查看区域的图片应该可以更大一下,否则都不能叫放大镜了嘛。

是这样,第二个效果其实不太难,主要是准备两个大小相差明显,长宽比例相同的清晰图片作为素材,把大的清晰图作为查看区的素材,把小一点的清晰图作为选择区的素材,这样就能保证左右两边看到的都是清晰的图,要是把小的图片放大作为右边的素材的话因为失真严重感觉好戳的,于是我没写。然后第一个效果你要是想看到的你自己实现以下吧。我喜欢给他人留点余地去发挥哈,我自己回头也再写写。

最后差点忘了补充下用rect怎么做了。如果用rect做的话,首先我是把rectedImage这个div里面的内容换成如下:<img src="demo.png" class="img"/><div class="mask"></div>,img的作用你肯定猜到了是用来操作rect的,而div.mask的作用我觉得说出来就很戳了,怎么做呢?我把这个div做成一个有很粗的边框的圆,rect之后的img不是正方形的吗?把圆形的div覆盖在被rect之后的img上,你就发现看起来还真是一个圆,因为div已经用自己的圆角把四四方方的img的四个角覆盖了。呵呵,这个办法也能实现,就是真心觉得有点戳。代码我就不贴出来了,你看过以后应该很快能实现出来了。

posted @ 2013-06-08 16:52  荒村听雨_  阅读(643)  评论(0编辑  收藏  举报