(网页)JavaScript 可折叠菜单错误

(HTML) JavaScript Collapsible Menu Error

本文关键字:菜单 错误 可折叠 JavaScript 网页      更新时间:2023-09-26

http://jsfiddle.net/xNnQ5/

我正在尝试使用JavaScript(和HTML)为我的网站创建一个可折叠的菜单(c_menu)。我希望它在用户单击div menu_open时打开,并在用户单击menu_close时关闭。但是,当我加载页面时,发生的所有情况只是菜单只是向上滚动,就好像我点击了menu_close,我没有。我该怎么办?


法典:


索引.html(仅一个片段)

<style type = "text/css">
#c_menu {
position: absolute;
width: 435px;
height: 250px;
z-index: 2;
left: 6px;
top: 294px;
background-color: #0099CC;
margin: auto;
</style>

<div id="menu_open"><img src="images/open.jpg" width="200" height="88" /></div>
<input type="button" name="menu_close" id="menu_close" value="Close"/>
<div id="c_menu"></div>

<script type = "text/javascript" src = "menu.js"> </script>

菜单.js(完整代码)

document.getElementById("c_menu").style.height = "0px";
document.getElementById("menu_open").onclick = menu_view(true);
document.getElementById("menu_close").onclick = menu_view(false);
function menu_view(toggle)
{
  if(toggle == true)
  {
      document.getElementById("c_menu").style.height = "0px";
      changeheight(5, 250, 0);
  }
  if(toggle == false)
  {
      document.getElementById("c_menu").height = "250px";
      changeheight(-5, 0, 250);
  }
}
function changeheight(incr, maxheight, init)
{
  setTimeout(function () {  
  var total = init; 
  total += incr; 
  var h = total + "px";
  document.getElementById("c_menu").style.height = h;                             
  if (total != maxheight) {            
     changeheight(incr, maxheight, total);            
  }                        
}, 5)
}

试试这个:

document.getElementById("menu_open").onclick = function() {menu_view(true)};
document.getElementById("menu_close").onclick = function() {menu_view(false)};

当您使用括号 ( ...onclick = menu_view(true) ),该函数会自动调用。

当你有一个没有参数的函数时,你可以像以前一样使用它,但没有括号:

document.getElementById("menu_open").onclick = menu_view;
document.getElementById("menu_close").onclick = menu_view;