在使用jQuery之前等待DOM更新offset() [英] Waiting for DOM update before using jQuery offset()

查看:104
本文介绍了在使用jQuery之前等待DOM更新offset()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码显示一个隐藏的元素,然后获取其大小:

I've got code that shows a hidden element and then gets its size:

var div = $('div.foo').show(); // Was hidden.

// Need to wait until the DOM is updated to get its offset
setTimeout(function() {
    var offset = div.offset();
    bar(offset.top, offset.left);
}, 0);

有没有一个更干净的方法来做,而不是推迟调用$ code> div.offset()与 setTimeout 0 ,还是这个最佳做法?我可以绑定一些DOM更新事件还是别的东西?

Is there a cleaner way to do this instead of a deferring the call to div.offset() with a setTimeout of 0, or is this best practice? Can I bind do some DOM update event or something else?

推荐答案

调用 .show() code>不传递持续时间参数是同步动作,因此不需要 setTimeout 。从文档


没有参数, .show()方法是显示元素的最简单方法[...]

With no parameters, the .show() method is the simplest way to display an element [...]

匹配的元素将立即显示,没有动画。这大致相当于调用 .css('display','block'),除了显示属性恢复到最初。

The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css('display', 'block'), except that the display property is restored to whatever it was initially.

如果您指定了一个持续时间,则可以传递一个回调函数,该函数将在动画完成时执行:

If you specify a duration however, you can pass a callback function which will be executed when the animation completes:

var div = $('div.foo').show(400, function() {
    var offset = $(this).offset();
    bar(offset.top, offset.left);
});

这篇关于在使用jQuery之前等待DOM更新offset()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆