开发者

Using js to determine if an element's width is determined by its content?

开发者 https://www.devze.com 2023-04-09 08:54 出处:网络
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 d

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.

0

精彩评论

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

关注公众号