[英]js style doesn't update
我有一段代碼讓我非常抓狂:我的網站中有一個水平菜單,並且在其中一個項目上的鼠標懸停事件中出現一個垂直子菜單。 我得到了這個工作。 html 看起來像這樣(暫時不要介意 js,評論也不在真正的 html 中):
<ul class="menu" onmouseout="menu('item',false)"> //the real html has some code to prevent nested elements 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>
但是,一些子菜單項比它們所屬的主菜單項更寬。 由於子菜單項是可變的,因此不可能硬編碼它們的寬度。 相反,我嘗試在鼠標懸停時獲取它們的寬度,然后我想將 ul 的寬度更改為最長項目的寬度。 我使用的 javascript 代碼是這樣的:
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;
}
}
}
如您所見,如果顯示菜單,則會保存原始寬度,並應用新寬度。 警報 function 提醒正確的新寬度。 但是,由於某種原因,新的寬度沒有顯示在頁面上。
我只是無法找出我做錯了什么。 誰能幫我?
編輯:我沒有想到純 css 解決方案。 但是,我仍然想知道為什么頁面沒有更新。 有人對此有答案嗎?
這似乎需要大量的工程來實現一些相當簡單的事情。 首先,您是否考慮過下拉結果的固定寬度。
接下來,您是否檢查了許多純 CSS 示例,所以您根本不需要使用 JavaScript?
http://csswizardry.com/2011/02/creating-a-pure-css-dropdown-menu/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.