开发者

Using jquery to get dimensions of hidden elements.

开发者 https://www.devze.com 2023-03-20 06:09 出处:网络
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 pa

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?


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.


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/


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消