我有一个搜索栏,上面有一个切换按钮。切换效果很好,但是我的问题是我想禁用 start 表单。我的切换按钮使用了 display 属性,但是当我通过CSS将该属性设置为禁用时,该切换将不再起作用。我还发现HTML中没有该属性,所以我很迷茫。这是我的Javascript旋转成HTML:
function ToggleSearchBar() {
var searchbar = document.getElementById("SearchBar");
if (searchbar.style.display == "none") {
searchbar.style.display = "";
} else {
searchbar.style.display = "none";
}
}
.search-button form {
display: none;
padding-top: 10px;
}
<div class="search-button">
<p onclick="ToggleSearchBar()">Search</p>
<form id="SearchBar">
<input type="text" placeholder="Your query here">
</form>
</div>
因此重申一下,我只需要form元素以显示为空,开始,同时仍然允许我的Javascript正常运行。任何帮助,将不胜感激。谢谢!
答案 0 :(得分:3)
这是因为当您设置display=""
时,它将使用其css样式,即none
。您应该将显示更改为block
。
为了隐藏/显示,我建议您使用Ternary operator
function ToggleSearchBar() {
var searchbar = document.getElementById("SearchBar");
if(searchbar.style.display === '') searchbar.style.display = 'block'
else searchbar.style.display = searchbar.style.display === 'none' ? 'block' : 'none'
}
.search-button form {
display: none;
padding-top: 10px;
}
<div class = "search-button">
<p onclick = "ToggleSearchBar()">Search</p>
<form id = "SearchBar">
<input type = "text" placeholder = "Your query here">
</form>
</div>
答案 1 :(得分:3)
这里的问题是element.style.display
访问内联样式属性以将该属性应用于您可以使用getComputedStyle
函数的元素
function ToggleSearchBar() {
var searchbar = document.getElementById("SearchBar");
var display = getComputedStyle(searchbar).display;
if (display == "none") {
searchbar.style.display = "block";
} else {
searchbar.style.display = "none";
}
}
.search-button form {
display: none;
padding-top: 10px;
}
<div class = "search-button">
<p onclick = "ToggleSearchBar()">Search</p>
<form id = "SearchBar">
<input type = "text" placeholder = "Your query here">
</form>
</div>
,并且您必须使用显示block
而不是空字符串,因为您的css声明为none
。