Using js to determine if an element's width is determined by its content?
I want to know if there's a way I can use jQuery or javascript to determine, given an element, if its width is set by a css style (either in开发者_JS百科line, inherited or directly) or if its being determined by the size/length of its content.
One idea comes to mind:
Store the element's
.width()
Remove all children of the element, move them elsewhere, or make them
display: none
Check out the element's
.width()
. If it has changed, it depended on the content. If it has not changed, it was set using CSS.Restore the children's
display
property or move them back if necessary.
Here is a very primitive prototype that simply removes all the element's content:
function determineWidth(jQueryElement)
{
var widthBefore = jQueryElement.width();
jQueryElement.html(""); // Empty the element
var widthAfter = jQueryElement.width();
if (widthAfter != widthBefore)
var result = "The width depended on the content.";
else
var result = "The width did NOT depend on the content.";
alert("Before: "+widthBefore+" After: "+widthAfter+" - "+result);
}
There's one side-effect for block level elements: Since their width doesn't depend on the content, the script will return "...did not depend...." even though the element may not have had an explicit width set in CSS as you require.
精彩评论