![](/img/trans.png)
[英]AngularJS: How to display element by default and toggle it when a button is pressed
[英]I want to make an element display when a button is pressed. by default the element is shown, how do I make it display none by default?
該按鈕的所有內容似乎正確,並且與我當前想要的相反。 當我加載頁面div時:myDIV在那並且按鈕切換它消失並重新出現。 如何默認使myDIV不設置,但仍具有按鈕功能作為切換
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
display:none;
}
</style>
</head>
<body>
<button onclick="myFunction()">test</button>
<div id="myDIV">
This is my DIV element.
</div>
<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>
我認為關鍵是在這里style.display =''實際上
使用style.display
獲取顯示狀態時,無法獲取CSS中定義的顯示屬性
您需要先獲取CSS值,才能使用JS中的按鈕切換顯示值。 默認情況下,建議不要在HTML上使用內聯樣式。
function myFunction() { const cont = document.querySelector("#chartContainer"); const styles = getComputedStyle(cont) const displayStyle = styles.display; if(displayStyle === "none"){ cont.style.display = "block"; }else { cont.style.display = "none"; } } const BTN = document.querySelector("button"); BTN.addEventListener('click', myFunction);
.container { background-color: #FFF; width: 100vw; height: 100vh; margin: 0; padding: 0; display: flex; } #chartContainer { background-color: blue; border-radius: 25px; height: 200px; width: 100%; float: below; display: none; } button { width: 50px; height: 50px; }
<div class="container"> <button>toggle</button> <div id="chartContainer"> </div> <script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.