jquery - 我可以使用变量显示通过 animate() 增加的 div 的宽度吗?

标签 jquery variables html jquery-animate width

是否可以使用 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

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

最佳答案

看看documentation 。您可以在动画函数中提供完整函数:

$('#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

关于jquery - 我可以使用变量显示通过 animate() 增加的 div 的宽度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18247692/

相关文章:

javascript - 无法让 jQuery 和 Web 服务很好地发挥作用

java - 变量未在线程中更新

css - 两个 div(菜单和内容)彼此相邻,边距透明

javascript - 尝试添加垂直 div 和其他内容被推下

javascript - 在站点中导航时如何保持单击按钮

javascript - JavaScript 中使用特殊字符分割变量

javascript - jquery 响应后滚动顶部保持位置

jquery - 受 Instagram 网络/桌面启发的搜索框

java - 如何访问数组方法中的参数? java

ios - UIImageView 的占位符变量