[英]Toggle Hiding/Showing an Element
I'm trying to have a couple of buttons to show and hide some pictures, I have gotten it to somewhat work, but when I start the webpage the pictures are already shown, when I try make them invisible at start.我试图有几个按钮来显示和隐藏一些图片,我已经让它有点工作,但是当我启动网页时,图片已经显示,当我尝试让它们在开始时不可见。 I have tried swapping the "block" and "none" sentences in the function, but it just made the button less responsive.
我曾尝试交换 function 中的“block”和“none”句子,但它只是让按钮的响应性降低。
javascript part: javascript 部分:
function bassnectar() {
var x = document.getElementById("myDIV3");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
html part: html 部分:
<button onclick="bassnectar()">Bassnectar</button>
<div id="myDIV3">
<img src="/images/bassnectar.jpg">
</div>
What you're missing is that you're assuming that block elements have a default display
value of block
.您缺少的是您假设块元素的默认
display
值为block
。 Which would be intuitive.这将是直观的。
Such is not the case though.但事实并非如此。
The initial value of display
is the browser's default. display
的初始值是浏览器的默认值。 If you query the value of the display
property on a new HTML element, you'll get an empty string.如果您在新的 HTML 元素上查询
display
属性的值,您将得到一个空字符串。
It doesn't return block
until you explicitly set its display
to block
.在您明确将其
display
设置为block
之前,它不会返回block
。
Edit:编辑:
It's important to note that setting a value in CSS doesn't change the behavior .请务必注意,在 CSS 中设置值不会改变行为。 If you set a div to be display block in CSS, it will still return an empty string if you query it.
如果你在 CSS 中设置一个 div 为显示块,你查询它仍然会返回一个空字符串。
Here's a working example:这是一个工作示例:
var block = document.createElement("div"); var inline = document.createElement("span"); console.log("Initial display values:") console.log(`block.style.display: ${block.style.display}`); console.log(`inline.style.display: ${inline.style.display}`); block.style.display = "block"; inline.style.display = "inline"; console.log("\nAfter setting them explicitly:") console.log(`block.style.display: ${block.style.display}`); console.log(`inline.style.display: ${inline.style.display}`);
div { display: block;important; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.