使用jquery获取隐藏元素的尺寸。
这是一个常见问题,但我对此有一点小小的改动,所以希望它不是重复的:
我有一种情况,我需要在使用 display 渲染的元素上触发
。在理想情况下,我会在页面上显示所有内容,然后隐藏需要隐藏的内容。不过,大多数客户讨厌渲染的“闪光”,因此他们通常会对此犹豫不决。.show()
:页面加载时无
我现在需要做的是获取设置为 display: none; 的元素的宽度。有很多方法可以做到这一点,但传统上有点老套,例如“克隆 html、设置为阻止、进行计算、删除克隆”类型的内容。
问题的“扭曲”是:是否有更新/更好/默认的标准方法可以使用最新版本的 jQuery (1.6.*) 来做到这一点?或者我们仍然恢复使用我们自己的解决方法?
This is a common question but I have a slight twist to it so hopefully it's not a duplicate:
I have a situation where I need to trigger .show()
on elements that are rendered with display: none
on page load. In ideal situations, I show everything on a page, then hide what needs to be hidden. Most clients hate the 'flash' of rendering, though, so they usually balk at that.
What I need to do now is grab the width of the element that is set to display: none; There are lots of ways to do this but traditionally have been a bit hacky such as 'clone the html, set to block, do your calculations, remove clone' type things.
The 'twist' to the question is: are there newer/better/default standard ways to do this with the more recent versions of jQuery (1.6.*)? Or do we still revert to rolling our own workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在某些情况下,您可以设置为position:absolute,visibility:hidden,display:block以使其具有适当的大小(尽管不受周围任何事物的限制,因为它已从布局中删除),但不可见且不可见影响页面的布局。然后,设置回显示:无,位置:静态和可见性:可见,将其恢复原样。
In some situations, you can set to position: absolute, visibility: hidden, display: block to cause it to have it's proper size (though not constrained by anything around it because it's been removed from the layout), but not be visible and not affect the layout of the page. Then, set back to display: none, position: static and visibility: visible to put it back the way it was.
通常,如果您在 css 文件中设置默认的高度-宽度,您应该能够获取隐藏元素的宽度/高度。
看这里:http://jsfiddle.net/qyJjh/
Usually if you set a default height-width in a css file you should be able to get the width/height of an hidden element.
Look here: http://jsfiddle.net/qyJjh/
我只会显示具有负边距的元素,例如 -99999px,绝对定位以避免破坏布局。然后你可以显示它并获取宽度和高度,我认为如果你这样做的话这并不是特别困难。
I would just show the element with negative margins such as -99999px, absolutely positioned to avoid breaking the layout. Then you can show it and get width and height, I don't think this is particularly hacky to do if you do it this way.