jQuery效果之封装一个文章图片弹出放大效果

首先先搭写一个基本的格式:

$.fn.popImg = function() {
    //your code goes here
}

然后用自调用匿名函数包裹你的代码,将系统变量以变量形式传递到插件内部,如下:

;(($,window,document,undefined){
    $.fn.popImg = () {
      your code goes here
    }
})(jQuery,document);

那么接下来我们就在里面实现点击文章图片弹出该图片并放大的效果。

整体代码如下:

;((){

      创建弹出层
      var $layer = $("<div>").css({
        position:'fixed',left:00'100%'9999999"#000"
      });

      复制点击的图片,获得图片的宽高以及位置
      var cloneImg = ($targetImg){
          var cloneW = $targetImg.width(),cloneH = $targetImg.height(),left = $targetImg.offset().left,top = $targetImg.offset().top;

          return $targetImg.clone().css({
              position:'fixed'
          });
      };

      让复制的图片居中显示
      var centerImg = ($cloneImg){
          var dW = $(window).width();
          var dH = $(window).height();
          $cloneImg.css('cursor','zoom-out').attr('clone-bigImg',true);
          var img = new Image();
          img.onload = (){
            $cloneImg.stop().animate({
                 width: this.width,height: .height,left: (dW - this.width) / 2this.height) / 2
            },300);
          }
          img.src = $cloneImg.attr('src');
      };
      
      this.each((){
          $(this).css('cursor','zoom-in').on('click',1)">(){
              var $body = $("body");
              $layer.appendTo($body);
              $layer.fadeIn(300);
              var $c = cloneImg($());
              $c.appendTo($body);
              centerImg($c);
          });
      });

    var timer = null;
    $(window).on("resize",1)">(){
      $("img[clone-bigImg]").each((){
        var $this = $();
        timer && clearTimeout(timer);
        timer = setTimeout((){
          centerImg($);
        },10);
      });
    });


    $(window).on("click keydown",1)">(evt){
      if(evt.type == "keydown" && evt.keyCode === 27) {
        $layer.fadeOut(300);
        $("img[clone-bigImg]").remove();
      }
      this = $(evt.target);
      if($this.attr("clone-bigImg")){
        $layer.fadeOut(300).remove();
      }
    });

  }
})(jQuery,document);

参考地址:http://barretlee.com/blog/2015/09/19/jquery-plugin-for-alert-img/

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...