js style doesn't update
I have a piece of code which is making me really crazy: I have a horizontal menu in my website, and on a mouseover event on one of the items a vertical submenu appears. I got this to work. The html looks something like this (don't mind the js for now, comments are also not in the real html):
<ul class="menu" onmouseout="menu('item',false)"> //the real html has some code to prevent nested element开发者_JS百科s to call the onmouseout event
<li id="itemLI">
<ul onmouseover="menu('item',true)">
<li><img src=somesource width=somewidth /></li>
<li class="drowdown item">submenuitem which is wider than the main menu item</li> //hidden until mouseover of the main item
</ul>
</li>
//somemoreitems
</ul>
However, some submenu items are wider than the main menu items they belong to. Since the submenu items are variable, it's impossible to hard-code their width. Instead I try to get their width on mouseover, and then I want to change the width of the ul to the width of the longest item. The javascript code I use is this:
var orwidth = 0;
function menu(menuItem,show)
{
//change menu width
var item = menuItem + "LI";
if (show)
{
//The important part which doesn't work
var element = document.getElementById(item);
var style = getComputedStyle(element,null);
orwidth = style.width;
element.style.width = "auto";
style = getComputedStyle(element,null);
alert(style.width);
}
else
{
document.getElementById(item).style.width = orwidth;
}
//show submenu
if (show)
{
var visible ="visible";
}
else
{
var visible = "hidden";
}
var lis = document.getElementsByTagName("li");
for (temp in lis)
{
if (lis[temp].className.indexOf("dropdown") != -1 && lis[temp].className.indexOf(menuItem) != -1)
{
lis[temp].style.visibility = visible;
}
}
}
as you can see, if the menu is shown the original width is saved, and a new width is applied. The alert function alerts the correct new width. However, for some reason the new width isn't shown on the page.
I just can't find out what I'm doing wrong. Can anyone help me?
edit: I didn't thought of the pure css solution. However, I still want to know why the page wasn't updated. Does anyone has the answer to that?
This seems like a lot of engineering to acheive something rather simple. Firstly, have you considered fixed widths for the drop-down results.
Next have you checked out the many many pure CSS examples out there, so you don't need to use JavaScript at all?
http://csswizardry.com/2011/02/creating-a-pure-css-dropdown-menu/
精彩评论