[英]javascript/jquery - how to get the width of an element / css class that hasn't been added to dom yet
I'm trying to dynamically find the width of an item which will have a css class with a specific width, in order to dynamically position its background image (a sprite). 我正在尝试动态地找到具有特定宽度的css类的项目的宽度,以便动态定位其背景图像(精灵)。 However, the item has not yet been added to the DOM.
但是,该项尚未添加到DOM中。 Is there a way to read a class's width property before it's added to the DOM?
有没有办法在添加到DOM之前读取类的宽度属性?
I believe you cant. 我相信你不能。 Instead add it to a test div,find the width and then remove the div.
而是将其添加到测试div,找到宽度,然后删除div。
$selector.append("<div id='test'></div>");
var widthVal= $selector.find("#test").width();
$("#test").remove();
selector is the element selector you may want to append to. selector是您可能想要追加的元素选择器。 You can associate a class with the "test" div, to have it as "display:none"
您可以将类与“test”div关联,将其设置为“display:none”
This is a Little Hackie but it should work. 这是一个小哈克,但它应该工作。 Add it to the DOM with the CSS Attribute
display: none
so it will be invisible then you can read the with property and delete the element if need be after. 使用CSS属性
display: none
将其添加到DOM display: none
这样它将不可见,然后您可以读取with属性并删除元素(如果需要)。 Or change its state from Display:none. 或者从Display:none更改其状态。
Hope this helped. 希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.