2012-01-01 38 views
0

我需要幫助摺疊頁面加載時的可摺疊div。在頁面加載時摺疊JavaScript/HTML div?

我用這段JavaScript代碼:

<script type="text/javascript"> 
    function switchMenu(obj) { 
     var el = document.getElementById(obj); 
     if (el.style.display != "none") { 
      el.style.display = 'none'; 
     } 
     else { 
      el.style.display = ''; 
     } 
    } 
    document.getElementById('aboutme').style.display = 'none'; 
</script> 

崩潰HTML DIV ID = 「aboutme」 當<a ...>about me</a>點:

<div class="container"> 
    <a href="#" onclick="switchMenu('aboutme');">about me</a> 
    <div id="aboutme"> 
     sample text to be expanded and collapsed 
    </div> 
</div> 

我不能讓頁面關閉我的div#aboutme頁面加載。

我希望這個頁面加載我的div摺疊。

我認爲JS線

document.getElementById('aboutme').style.display = 'none'; 

應該做的伎倆,但事實並非如此。我究竟做錯了什麼?

感謝您的幫助。

+1

只需將腳本後html代碼 – naveen 2012-01-01 12:18:08

+0

你可以發佈一個不起作用的實例嗎? jsfiddle是一個很好的地方,那麼我們會更容易幫忙。 – 2012-01-01 12:27:08

回答

2

如果你希望你的div來加載倒塌,只需編寫以下

<div id="aboutme" style="display:none"> 
     sample text to be expanded and collapsed 
    </div> 

這應該解決的問題。 但是,如果您仍然對JavaScript解決方案感興趣,請繼續閱讀。
正如你所說I can't get the page to close my div#aboutme on page load - 問題是你沒有使用「onload」事件。 簡而言之行document.getElementById('aboutme').style.display = 'none';在你的身體的onload屬性.. 像這樣

<body onload="document.getElementById('aboutme').style.display = 'none';"> 
... 
</body> 

,你會看到使用JavaScript的結果。我建議你改用「風格」方法。好多了。

+0

謝謝!這個html解決方案正是我正在尋找的簡單方法。 – mplewis 2012-01-01 22:39:59

1

究竟如何讓JS運行在窗口加載?它可能只是在頁面呈現之前運行

請點擊鏈接工作?如果是這樣,那就證明問題只是加載順序

最簡單的解決方案是將代碼放在HTML文件的最後,就在關閉</body>標記之前。下面的代碼更通用,可以放在任何地方。需要注意的是切換鏈路回我將顯示器設置爲「內聯」(或塊,即不管它是什麼之前 - 你可能想的是保存到一個變量,以確保)

<script type="text/javascript"> 
function switchMenu(id) { 
    var el = document.getElementById(id); 
    if (el.style.display != "none") { 
     el.style.display = 'none'; 
    } 
    else { 
     el.style.display = 'inline'; //or block - i.e. whatever it is rendered by 
    } 
} 

//add to the window onload event 
if(window.addEventListener){ 
    window.addEventListener('load', function(){ switchMenu('aboutme')}, false); 
} else if (window.attachEvent) { 
    window.attachEvent("onload", function(){ switchMenu('aboutme') }); 
} 
</script> 
+0

感謝您的解決方案! – mplewis 2012-01-01 22:39:44