2017-08-31 82 views
0

我正在從w3學校調整此代碼,但代碼的內容在頁面刷新時暴露,點擊時摺疊。我希望內容開始隱藏,並且只在按鈕被擊中時纔會發現。切換按鈕開始關閉,而不是在

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<style> 
 
#myDIV { 
 
    width: 100%; 
 
    padding: 50px 0; 
 
    text-align: center; 
 
    background-color: lightblue; 
 
    margin-top:20px; 
 
} 
 
</style> 
 
</head> 
 
<body> 
 

 
<p>Click the "Try it" button to toggle between hiding and showing the DIV  element:</p> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<div id="myDIV"> 
 
This is my DIV element. 
 
</div> 
 

 
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p> 
 

 
<script> 
 
function myFunction() { 
 
    var x = document.getElementById('myDIV'); 
 
    if (x.style.display === 'none') { 
 
     x.style.display = 'block'; 
 
    } else { 
 
     x.style.display = 'none'; 
 
    } 
 
} 
 
</script> 
 

 
</body> 
 
</html>

+0

的[切換顯示使用JavaScript的div可能的複製。開始隱藏,點擊揭示](https://stackoverflow.com/questions/41765069/toggle-reveal-div-with-javascript-start-hidden-click-to-reveal) – PedroSouki

回答

3
<div id="myDIV" style="display:none;"> 
    This is my DIV element. 
</div> 
+0

我建議,而不是「顯示:無「在已經在代碼片段中定義的CSS部分中。更好地在CSS上完成默認行爲,並通過類或某些情況直接在元素上添加更改(即使我認爲那是不好的練習) – Fyllekanin

+0

有效的點。更改css類:https://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript – mchan