简体   繁体   English

javascript / jquery - 如何获取尚未添加到dom的元素/ css类的宽度

[英]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.

相关问题 jQuery:如何在尚未添加到DOM的元素上调用jQuery插件函数? - jQuery: How to call a jQuery plugin function on an element that hasn't yet been added to the DOM? 如何在尚未渲染的元素中应用 css class? - How to apply a css class in a element that hasn't been rendered yet? 如何将 Javascript 事件处理程序注册到尚未添加到页面的元素 - How do I register a Javascript event handler to an element that hasn't been added to the page yet 尚未添加到页面的选择器的jQuery add事件 - jQuery add event for a selector that hasn't been “added” to page yet 如何选择尚未创建的元素? - How do I select an element that hasn't been created yet? dojo-如果尚未将节点添加到dom中,如何通过id获得节点? - dojo - How to get node by Id if it has not been added to the dom yet? 扩展尚未创建的javascript(nodeJS)对象 - Extending a javascript (nodeJS) object that hasn't been created yet 仅在先前未使用jQuery添加元素的情况下,才在元素集之后添加元素 - Add element after a set of elements only if it hasn't been added previously using jQuery 如何显示尚未上传的图像? - How to display an image that hasn't been uploaded yet? 在第二次单击后添加标记 state 尚未使用您添加的新项目进行更新? - the marker is added after the second click state hasn't been updated with the newItem you added yet?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM