【问题标题】:How to make a simple show/hide button work?如何使简单的显示/隐藏按钮起作用?
【发布时间】:2020-09-05 18:55:11
【问题描述】:
我只是想找出...为什么我必须单击 2 次(而不是单击 1 次)直到第一次出现文本?你能给我一些帮助来解决这个问题吗?
谢谢!
function mudar() {
var x = document.getElementById("texto");
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.escondido {
display: none;
}
<button onclick=mudar()>EXIBIR E ESCONDER O TEXTO</button>
<p class="escondido" id="texto">Texto para exibir e esconder</p>
【问题讨论】:
标签:
javascript
html
button
display
【解决方案1】:
这是另一种方法,切换类,将样式与“业务逻辑”分离:
<html>
<head>
<style>
.escondido {
display: block;
}
.escondido-hidden {
display: none;
}
</style>
</head>
<body>
<button onclick=mudar()>EXIBIR E ESCONDER O TEXTO</button>
<p class="escondido escondido-hidden" id="texto">Texto para exibir e esconder</p>
<script>
function mudar() {
var x = document.getElementById("texto");
x.classList.toggle('escondido-hidden')
}
</script>
</body>
</html>
【解决方案2】:
要获得显示属性,请使用getComputedStyle(),它“在应用活动样式表并解决这些值可能包含的任何基本计算之后,返回一个包含元素所有 CSS 属性值的对象”
function mudar() {
var x = document.getElementById("texto");
var display = window.getComputedStyle(x).getPropertyValue('display');
if (display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.escondido {
display: none;
}
<button onclick=mudar()>EXIBIR E ESCONDER O TEXTO</button>
<p class="escondido" id="texto">Texto para exibir e esconder</p>
【解决方案3】:
这是因为最初 style 中的 display 属性是一个空字符串“”。并且您的代码直接执行到 else 块。您可以添加条件来检查显示属性值是否为空字符串。
function mudar() {
var x = document.getElementById("texto");
console.log(x.style.display)
if (x.style.display == "none" || x.style.display == "") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.escondido {
display: none;
}
<button onclick=mudar()>EXIBIR E ESCONDER O TEXTO</button>
<p class="escondido" id="texto">Texto para exibir e esconder</p>
【解决方案4】:
当你的程序启动时,x.style.display的值不是"none",而是空字符串。
只需添加:
|| x.style.display == ""
这应该可以按预期工作。
function mudar() {
var x = document.getElementById("texto");
if (x.style.display == "none" || x.style.display == "") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.escondido {
display: none;
}
<button onclick=mudar()>EXIBIR E ESCONDER O TEXTO</button>
<p class="escondido" id="texto">Texto para exibir e esconder</p>
【解决方案5】:
你可以改变
if (x.style.display == "none") {
到
if (x.style.display === "" || x.style.display == "none") {