当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery实现文章图片弹出放大效果

jQuery实现文章图片弹出放大效果

2019年05月24日  | 移动技术网IT编程  | 我要评论

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

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

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

;(function($,window,document,undefined){
  $.fn.popimg = function() {
   //your code goes here
  }
})(jquery,window,document);

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

整体代码如下:

;(function($,window,document,undefined){
 $.fn.popimg = function(){

   //创建弹出层
   var $layer = $("<div>").css({
    position:'fixed',
    left:0,
    right:0,
    top:0,
    bottom:0,
    width:'100%',
    height:'100%',
    zindex:9999999,
    display:'none',
    background: "#000",
    opacity:'0.6'
   });

   //复制点击的图片,获得图片的宽高以及位置
   var cloneimg = function($targetimg){
     var clonew = $targetimg.width(),
       cloneh = $targetimg.height(),
       left = $targetimg.offset().left,
       top = $targetimg.offset().top;

     return $targetimg.clone().css({
       position:'fixed',
       width:clonew,
       height:cloneh,
       left:left,
       top:top,
       zindex:10000000
     });
   };

   //让复制的图片居中显示
   var centerimg = function($cloneimg){
     var dw = $(window).width();
     var dh = $(window).height();
     $cloneimg.css('cursor','zoom-out').attr('clone-bigimg',true);
     var img = new image();
     img.onload = function(){
      $cloneimg.stop().animate({
         width: this.width,
        height: this.height,
        left: (dw - this.width) / 2,
        top: (dh - this.height) / 2
      },300);
     }
     img.src = $cloneimg.attr('src');
   };

   this.each(function(){
     $(this).css('cursor','zoom-in').on('click',function(){
       var $body = $("body");
       $layer.appendto($body);
       $layer.fadein(300);
       var $c = cloneimg($(this));
       $c.appendto($body);
       centerimg($c);
     });
   });

  var timer = null;
  $(window).on("resize", function(){
   $("img[clone-bigimg]").each(function(){
    var $this = $(this);
    timer && cleartimeout(timer);
    timer = settimeout(function(){
     centerimg($this);
    }, 10);
   });
  });

  $(window).on("click keydown", function(evt){
   if(evt.type == "keydown" && evt.keycode === 27) {
    $layer.fadeout(300);
    $("img[clone-bigimg]").remove();
   }
   var $this = $(evt.target);
   if($this.attr("clone-bigimg")){
    $layer.fadeout(300);
    $("img[clone-bigimg]").remove();
   }
  });
 }
})(jquery,window,document);

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网