【问题标题】:Jquery - Expand image height and width 20% on hoverJquery - 悬停时扩展图像高度和宽度 20%
【发布时间】:2010-09-02 19:58:25
【问题描述】:

晚安 - 动态访问图像高度和宽度的最佳方式是什么。
我想为图像的宽度和高度添加 20% 并在周围的 div 悬停时设置动画,我想我需要使用“this”,但不知道如何访问图像。

任何帮助都得到了极大的帮助。

干杯保罗

【问题讨论】:

    标签: jquery this jquery-animate


    【解决方案1】:

    你可以这样做,使用带有函数参数的.height().width()

    $("img").hover(function() {
        $(this).height(function(i, h) { return h * 1.2; })
               .width(function(i, w) { return w * 1.2; });
    }, function() {
        $(this).height(function(i, h) { return h / 1.2; })
               .width(function(i, w) { return w / 1.2; });
    });​
    

    You can give it a try here,如果你想要一个流畅的动画,你可以存储初始高度/宽度和.animate(),像这样:

    $("img").each(function() {
        $.data(this, 'size', { width: $(this).width(), height: $(this).height() });
    }).hover(function() {
        $(this).stop().animate({ height: $.data(this,'size').height*1.2, 
                                 width: $.data(this,'size').width*1.2 });
    }, function() {
        $(this).stop().animate({ height: $.data(this,'size').height, 
                                 width: $.data(this,'size').width });
    });​
    

    You can give it a try here,请务必在$(window).load() 中运行这些选项中的任何一个,并且不要 $(document).ready(),因为可能尚未加载尺寸。

    【讨论】:

      【解决方案2】:

      使用jQuery的widthheight方法:

      $(".divs").mouseover(function() {
      
          var $div = $(this);
          var $item = $div.find("img");
      
          var width = $item.width();
          var height = $item.height();
      
          width = width * 1.2;
          height = height * 1.2;
      
          $item.width(width);
          $item.height(width);
      });
      

      【讨论】:

        【解决方案3】:
        $("#divId").mouseover(function() {
            var o = $("#imgid");
            o.width(o.width()*1.2).height(o.height()*1.2);
        });
        

        【讨论】:

          【解决方案4】:

          这是一种使用动画的方法,它应该提供更平滑的过渡:

          $("img").hover(function() {
              var $this = $(this);
              $this.animate({
                  'height': $this.height() * 1.2,
                  'width' : $this.width() * 1.2
              });
          },function() {
                 var $this = $(this);
                 $this.animate({
                  'height': $this.height() / 1.2,
                  'width' : $this.width() / 1.2
              });
          });
          

          【讨论】:

          • 这不会像预期的那样工作,因为如果你在动画完成之前悬停在/悬停,新的 .height().width() 值将不是它们的目标值,这意味着它我会回到其他尺寸 :) 在这里试试:jsfiddle.net/nick_craver/JqDMR 我所做的唯一更改是 $this 未在您的代码中定义 :)
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-05-16
          • 1970-01-01
          • 1970-01-01
          • 2013-08-03
          • 2013-04-02
          • 1970-01-01
          • 2014-07-12
          相关资源
          最近更新 更多