我编写了一些javascript代码来实现 <div>
的出现或消失。
[src.js]
openSearch = () => {
var con = document.getElementById("search-bar");
if(con.style.display == 'none') {
con.style.display = 'block';
} else {
con.style.display = 'none';
}
}
[style.css]
#search-bar {
position: absolute;
height: 4em;
width: 20em;
background-color: white;
border: 1px solid black;
padding: 1.5rem;
right: 0;
display: none;
}
在 <a>
标签中添加 onclick="openSearch()"
。
第一次点击 <a>
标签时,它不起作用。
但是再次点击后,它就能正常工作了。
因此我尝试使用 console.log(document.getElementById("search-bar").style.display) 输出,结果为空白字符。
我想知道为什么我已经将 display: none
定义到 search-bar
上了,但是 search-bar
的初始 style.display 值为空白字符呢?
如何解决这个问题?
display:none
。当你检查con.style.display
时,第一次它是空的。div.style
不是计算出来的样式,而是div上属性style
的值。 - dube.style
属性仅包含直接设置在元素上的样式。要包括样式表应用的样式,您可以使用getComputedStyle()
。 - Jonathan Lonowski