我创建了一个简单的函数,用于在单击按钮时显示或隐藏div标记,但如何将其设置为初始隐藏,并在单击按钮后显示?
发布于 2021-07-16 13:24:21
只需将其display
样式属性设置为None
即可。
element = document.getElementById('toggle');
button = document.getElementById('toggle-button');
function hideAndShow(){
if(element.style.display == 'none'|| element.style.display == '') // checks if the display property is set to none or not
{
element.style.display = 'Block'; // if set to none then set the display property to block
button.innerHTML = 'Hide'; // changes the button's text
}
else{
element.style.display = 'None'; // otherwise set it to none
button.innerHTML = 'Show';
}
}
#toggle{
width: 100%;
margin: auto;
height: 50px;
display: None; /*this set's the divison to a hidden state by default*/
background-color: rgba(248,25,34,0.8);
}
#toggle-button{
width: 100%;
margin: 5px;
height: 25px;
padding: 5px;
color: rgba(25,25,67,0.5);
}
<div id='toggle'></div>
<button id='toggle-button' onclick='hideAndShow()'>Show</button>
发布于 2021-07-16 13:02:17
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
};
发布于 2021-07-16 13:02:23
function toggle() {
document.getElementById('test').style.display = 'block';
}
.hide {
display: none;
}
<div id="test" class="hide">Test</div>
<button onclick="toggle()">Toggle</button>
https://stackoverflow.com/questions/68403626
复制相似问题