2013-10-29 70 views
0

http://jsfiddle.net/xNnQ5/(HTML)的JavaScript可摺疊菜單錯誤

我想使用JavaScript(和HTML)創建爲我的網站可摺疊菜單(c_menu)。我希望在用戶點擊div menu_open時打開它,並在用戶點擊menu_close時關閉。但是,當我加載頁面時,所發生的只是菜單向上滾動,就好像我點擊了menu_close,而我沒有。我該怎麼辦?


代碼:


的index.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> 

menu.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) 
} 
+0

你可以提供一個小提琴? – Arjun

+0

@Arjun - http://jsfiddle.net/xNnQ5/ – Joe

+1

@ xtof的答案根據您的要求工作,我想! – Arjun

回答

1

試試這個:

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;