简体   繁体   English

在JavaScript HTML中展开折叠菜单

[英]Expand Collapse Menu in JavaScript HTML

I have found this code to make a menu that collapses when the user clicks on the minus sign within a page. 我发现此代码可以使菜单在用户单击页面内的减号时折叠。 But the menu shows all the contents within the Main Item when the page first loads. 但是,当页面首次加载时,菜单会显示“主要项目”中的所有内容。 I would like to make the page show just the Main Item when the page loads. 我想让页面在加载时仅显示Main Item。 This is the code: 这是代码:

    <script langauge="JavaScript" type="text/javascript">
function doMenu(item) {
 obj=document.getElementById(item);
 col=document.getElementById("x" + item);
 if (obj.style.display=="none") {
  obj.style.display="block";
  col.innerHTML="[-]";
 }
 else {
  obj.style.display="none";
  col.innerHTML="[+]";
 }
}
</script>
</head>
<body>
<a href="JavaScript:doMenu('main');" id=xmain>[+]</a> Main Item
<div id=main style="margin-left:1em">
 <a href=#>Item 1</a><br>
 <a href=#>Item 2</a><br>
 <a href=#>Item 3</a>
</div>
<br>
</body>
</html>

I would be very grateful if someone could show me how to change the code to do this. 如果有人可以向我展示如何更改代码来做到这一点,我将非常感激。

Thanks 谢谢

Change: 更改:

<a href="JavaScript:doMenu('main');" id=xmain>

to: 至:

<a href="JavaScript:doMenu('main');" style="display: none;" id=xmain>

BTW, as some side notes the code you found is not very good. 顺便说一句,正如某些方面所述,您发现的代码不是很好。 If this is intended as a professional project I wouldn't use it. 如果这是一个专业项目,我不会使用它。

For one, I would change: 首先,我将更改:

obj.style.display="block";

to: 至:

obj.style.display="";

To avoid some bugs in certain browsers. 避免某些浏览器中的错误。

window.addEventListener('load', function(){
    document.getElementById('main').style.display = 'none';
}, false);

I think that changing 我认为改变

<div id=main style="margin-left:1em">

to

<div id=main style="margin-left:1em; display:none">

should work. 应该管用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM