簡體   English   中英

頁面加載時JavaScript / HTML div崩潰了嗎?

[英]Collapsing JavaScript/HTML div on page load?

我需要在頁面加載時折疊可折疊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>

點擊<a ...>about me</a>時,折疊HTML div id =“ aboutme”:

<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';

應該可以解決問題,但事實並非如此。 我究竟做錯了什么?

謝謝你的幫助。

如果您希望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查看結果。 我建議您改用“樣式”方法。 好多了。

究竟如何使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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM