【问题标题】:Can I display the width of a div increased with animate() using a variable?我可以使用变量显示随着 animate() 增加的 div 的宽度吗?
【发布时间】:2013-08-17 08:20:37
【问题描述】:

是否可以使用 animate() 动态增加 div 的宽度 并将其显示在变量中?

我已经尝试了几件事,但变量仍然显示 div 的原始宽度(至极为零)所以它没有被更新。

HTML

<a href="#" id="button2">Add width</a>
<div id='content'></div>
<div id="msg"></div>

jQuery

$('#button2').click(function () {
    $('#content').animate({
        width: '+=40'
    }, 500);
});

var width = $('#content').width();
$("#msg").html(width);

Demo

所以我想知道如何才能做到这一点。我应该为变量写一个更新函数还是有更简单的方法?

【问题讨论】:

标签: jquery variables html jquery-animate width


【解决方案1】:

看看 documentation。您可以在 animate 函数中提供complete 函数:

$('#content').animate({
        width: '+=40'
    }, 500, function () {
      var width = $('#content').width();
      $("#msg").html(width);
});

或者,使用带有两个参数(属性和选项)的重载方法:

$('#button2').click(function () {
    $('#content').animate({
        width: '+=40'
    }, {
        step: function () {
            var width = $('#content').width();
            $("#msg").html(width);
        }
    })
});

FIDDLE DEMO

【讨论】:

    【解决方案2】:
    $('#button2').click(function () {
        $('#content').animate({
            width: '+=40'
        }, 500, function() {
            var width = $('#content').width();
            $("#msg").html(width);
        });
    
    });
    

    【讨论】:

      【解决方案3】:

      使用动画回调..

      您的代码仅在开始时检查和更新宽度一次。 每次动画更新内容的宽度时,您都必须这样做。 为此,您可以使用 animate 方法的回调。

      $('#button2').click(function () {
          $('#content').animate({
              width: '+=40'
          }, 500, function(){
              var width = $('#content').width();
              $("#msg").html(width);
          });
      });
      

      回调是作为'animate'的第三个参数传递的函数,在动画结束时调用。

      工作小提琴:http://jsfiddle.net/7asv2/4/

      【讨论】:

        【解决方案4】:

        您可以添加一个在动画的任何步骤上调用的函数

        $('#content').animate({
                width: '+=40'
            }, {
                step: function (w) {
                    msg.html(w);
                },
                duration: 500,
                easing: "linear"
            });
        

        fiddle

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-11
          • 1970-01-01
          • 1970-01-01
          • 2016-02-29
          • 1970-01-01
          • 2020-06-06
          相关资源
          最近更新 更多