该按钮的所有内容似乎正确,并且与我当前想要的相反。当我加载页面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>
答案 0 :(得分:0)
我认为要点是style.display = '' actually do
使用style.display
获取显示状态时,它无法获取css中定义的显示属性
答案 1 :(得分:0)
您需要先获取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>