getElementById()。style.display不起作用 [英] getElementById().style.display does not work
问题描述
我为< div>
出现或消失了一些js代码。
[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;
身高:4em;
width:20em;
背景颜色:白色;
border:1px纯黑色;
填充:1.5rem;
right:0;
display:none;
}
并添加 onclick =openSearch()
到< a>
标记。 当我点击< a>
标签第一次,它不起作用。
但再次点击,它工作正常。
所以我尝试了console.log(document.getElementById(search-bar)。style.display,它会抛出(空白)。
我想知道为什么我要定义 display:none
到 search-bar
,但为什么要使用初始样式。显示 search-bar
为空白值?
我该如何解决它?
或者,您可以将显示样式移动到另一个类并切换类。
openSearch =()=> {var con = document.getElementById(s操作搜索条); con.classList.toggle(hidden);}
#search-bar {position:absolute;身高:4em;宽度:20em;背景颜色:白色;边框:1px纯黑色;填充:1.5rem; right:0;}。hidden {display:none;}
< a onclick =openSearch()>切换< / a> < div id =search-barclass =hidden>一些文字在这里< / div>
I made some js code for <div>
to appear or disappear.
[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;
}
and add onclick="openSearch()"
to <a>
tag.
When I click the <a>
tag first time, it doesn't work anything.
But click again, it works properly.
So I tried to console.log(document.getElementById("search-bar").style.display, it throws ""(blank).
I wonder that I defined display: none
to search-bar
but why initial style.display of search-bar
is blank value?
And how can I fix it?
Alternatively, you can move the display style to another class and can toggle class.
openSearch = () => {
var con = document.getElementById("search-bar");
con.classList.toggle("hidden");
}
#search-bar {
position: absolute;
height: 4em;
width: 20em;
background-color: white;
border: 1px solid black;
padding: 1.5rem;
right: 0;
}
.hidden {
display: none;
}
<a onclick="openSearch()">Toggle</a>
<div id="search-bar" class="hidden">Some text here</div>
这篇关于getElementById()。style.display不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!