调整大小后获取元素的宽度

发布于 2024-08-29 15:17:29 字数 340 浏览 4 评论 0原文

使用 $(el).css() 调整元素大小后是否可以获取元素的大小?

我的代码是:

function resize() {
    $(".combobox").css('width', '100%');
    var width = $(".combobox").width();
}

只有在第二次调用该函数后,我才获得组合框的实际值。第一次是在执行 $(".combobox").css('width', '100%'); 之前获取宽度

我认为这是 .css() 之后没有重新创建 DOM 的错误。有没有办法强制 DOM 重新加载?

提前致谢!

Is it possible to get the size of an element after resizing it using $(el).css()?

My code is:

function resize() {
    $(".combobox").css('width', '100%');
    var width = $(".combobox").width();
}

I've get the real value of the combobox only after calling the function a second time. The first time is gets the width before executing $(".combobox").css('width', '100%');

I suppose this is fault of the DOM not being recreated after the .css(). Is there any way to force DOM reloading?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

与往事干杯 2024-09-05 15:17:41

尝试链接两个函数:

function resize() {
    var width = $(".combobox").css('width', '100%').width();
}

Try chaining the two functions:

function resize() {
    var width = $(".combobox").css('width', '100%').width();
}
热血少△年 2024-09-05 15:17:39

尝试将获取宽度的代码部分放入计划为 1 毫秒的计时器中...

在执行脚本时,浏览器不会执行调整大小计算。如果你安排一个计时器并退出 JS 函数,浏览器将更新所有已更改的 DOM 元素的状态,然后启动计时器,因此此时组合框的宽度已更新。

我在基于 GWT 的网页中使用了非常类似的东西。

这个技巧不仅适用于 JS,而且适用于许多 GUI 框架,这些框架以延迟的方式进行布局。

Try putting the part of the code that gets the width in a timer scheduled for 1 millisecond...

The browser won't do the resize calculation while the script is executing. If you schedule a timer and exit the JS function, the browser will update the state of all the DOM elements that changed, and then launch the timer, so by then the width of your combobox has updated.

I used something very similar in a GWT based webpage

This trick works not only for JS but in many GUI frameworks, which do layout in a delayed way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文