I am generating specific DOM elements dynamically for a specific layout. In certain cases I am able to get the width of a previously created element using jQuery (to determine other layout factors).
var width = parseInt((jQuery(element).css("width")));
However this only works after the element has been appended to the window. Is there any way to get the theoretical width of an element which is generated, but not yet appended to the window?
(Extra info: Down at the function's bare bones, I am simply generating these with a document.createElement()
)
This isn't very practical or useful but I just wrote this function which creates a 'sandbox' by cloning the parent and placing it in the dom offscreen.
var getStyle = function($parent, $element, props){
if(typeof props == 'string'){props = [props];}
var $sandbox = $parent.clone().css({
position: 'absolute',
display: 'inline-block',
width: $parent.width(),
height: $parent.height(),
top: -1000,
left: -1000
});
$('body').append($sandbox);
$sandbox.append($element);
var result = {};
for(var i=0;i<props.length;i++){
var p = props[i];
if(p == 'width'){ result[p] = $element.width(); }
else if (p == 'height'){ result[p] = $element.height(); }
else{ result[p] = $element.css(p); }
}
$sandbox.remove();
return result;
}
console.log(
getStyle(
$('#name'), //parent
$('<div>helo</div>'), //new elemen
['width','height','color'] //properties to fetch
)
);
http://jsfiddle.net/beXyM/1/
精彩评论