Get width of ul in jQuery
I need to get the width of a <ul>
which has a dynamic width, in order to set the width for its enclosing <li>
s to the width of the <ul>
for IE7.
The <开发者_高级运维;ul>
is styled display:block
. Currently jQuery's .width()
returns 0
. I tried to get the widest <li>
's width, because it sets the width for the <ul>
's but here, I get 0
, too?
Is there any way (or workaround) to get the width of the <ul>
or its <li>
s?
Laura
jQuery doesn't like hidden elements: jQuery - Get Width of Element when Not Visible (Display: None)
Try to use the method "offsetWidth":
<ul id="MyElement" style="display:block;visibility:hidden;">
<li>Hello World!</li>
<li>Hellow Web!</li>
</ul>
<script type="text/javascript">
alert(document.getElementById('MyElement').offsetWidth);
</script>
It should return an element's dynamic width.
Or if you want jQuery try to add this to your jQuery file (jquery.js)
jQuery.fn.offsetWidth = function () {
return this.offsetWidth;
}
If it's set to hidden (seems to be the problem) and still returns 0 as width, try to clone the element (the element you want to get the width from). Set css position:absolute; left:-200; top -200;visibility:visible;
of your element copy. Get the width of the element copy either jQuery or just JavaScript. Remove the element copy. You should now get the width. The top
and left
is set negative so the element copy won't appear on your screen.
Note that this can make your execution a little bit slower.
Are you writing your script as a part of $(document).ready() handler? Like:
$(document).ready(function() {
// Here.
});
Or is it run when the page is loading?
Maybe your script is executed before the width of the <ul>
is set.
Do you need the list items to have bullets? If you don't, this can be solved with CSS only, by applying display:block
to the <li>
s.
The way I do dropdowns is to set them to be position: absolute and left: -5000px (instead of display: none). That way you can just set/remove the "left" property when you want to hide/show them, and the dimensions of the element are always available. Since you haven't posted any code/markup, I'm not sure if this suggestion would work in your situation, but I thought I'd throw it out there.
As for answering your question, you should use offsetWidth, and remember to add the padding, border width, and margin values of the element to the offsetWidth too.
精彩评论