cl1*_*10k 2 html javascript css
我正在尝试通过在display:none和display:block之间切换来调整w3schools.com中的函数以切换div的可见性.
所述div的显示属性通过css定义.如果显示最初设置为"阻止",则一切正常,但如果最初设置为"无"则不行.
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}Run Code Online (Sandbox Code Playgroud)
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
display : block;
}Run Code Online (Sandbox Code Playgroud)
<p>Click the button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Click</button>
<div id="myDIV">
This is my DIV element.
</div>Run Code Online (Sandbox Code Playgroud)
请参阅此codepen示例.如果你将css更改为display:none; 你需要在div切换到阻止之前单击按钮两次(!).为什么脚本不能识别最初的'none'?
问题是您最初是display通过style对象的属性获取属性值.但是,该属性仅返回应用于元素的"内联"样式,如下所示:
<div style="display:none;">something</div>
Run Code Online (Sandbox Code Playgroud)
由于您display:none通过单独的"内部样式"而不是内联样式进行设置,因此返回的初始值为x.style.display空字符串,因此您的代码执行将落入语句的else分支中,if然后为该元素设置新的内联样式.这就是为什么它适用于第二次点击 - 第一次点击实际上创建了一个之前不存在的内联样式,因此第二次点击有效.
您应该使用window.getComputedStyle(x).display;获取值,因为.getComputedStyle()获取属性值无论在元素上设置的位置或方式如何.
function myFunction() {
var x = document.getElementById("myDIV");
var displayValue = window.getComputedStyle(x).display;
if (displayValue === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}Run Code Online (Sandbox Code Playgroud)
#myDIV {
display:none;
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}Run Code Online (Sandbox Code Playgroud)
<p>Click the button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Click</button>
<div id="myDIV">
This is my DIV element.
</div>Run Code Online (Sandbox Code Playgroud)
说到这一点,使用内联样式通常被认为是最后的手段,因为代码必须具有多么精细,它们如何导致代码重复,代码的不可扩展性以及覆盖内联样式的难度.提前设置CSS类然后根据需要将这些类应用或删除到元素要简单得多.DOM元素支持一个.classList属性,提供添加,删除和切换类的简单方法(切换是你想要的).这种方法使实际的功能代码更加简单:
function myFunction() {
document.getElementById("myDIV").classList.toggle("hidden");
}Run Code Online (Sandbox Code Playgroud)
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
/* This class will be added, removed or toggled as needed.
It is kept separate from the element's style so that only
this property can be toggled as needed without affecting
the other styling of the element. Also, it can be used
for any other elements (as needed) that may need to be
hidden at some point. */
.hidden { display:none; }Run Code Online (Sandbox Code Playgroud)
<p>Click the button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Click</button>
<!-- Notice that the element has the class applied to it from the start
to ensure that the element is hidden from the start. -->
<div id="myDIV" class="hidden">This is my DIV element.</div>Run Code Online (Sandbox Code Playgroud)