[英]document.getElementById().style.display = “block” doesnt work in same function as document.getElementById().innerText
[英]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;
height: 4em;
width: 20em;
background-color: white;
border: 1px solid black;
padding: 1.5rem;
right: 0;
display: none;
}
並將onclick="openSearch()"
到<a>
標記。
第一次單擊<a>
標記時,它沒有任何作用。
但是再次單擊,它可以正常工作。
所以我試圖console.log(document.getElementById(“ search-bar”)。style.display,它拋出“”(空白)。
我不知道,我定義display: none
到search-bar
,但為什么最初的style.display search-bar
是空白的價值?
我該如何解決?
或者,您可以將顯示樣式移至另一個類並可以切換類。
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>
function openSearch()
{
var div = document.getElementById("search-bar");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
}
您可以嘗試通過js將樣式初始化為無:
document.getElementById("search-bar").style.display = 'none';
頁面加載時。 我的猜測是可以的。
[解決了]
首先,我添加display: none
到css文件。
但是在對標簽使用style="display: none"
,它可以正常工作。
也許我認為有加載優先級,但是我不知道為什么。
當您在CSS中設置display:none
,它像display=""
一樣是單調的。 而不display=none
。 結果是相同的,但是如果您選擇display='none'
他將返回false。您可以這樣嘗試:
openSearch = () => {
var con = document.getElementById("search-bar");
if(con.style.display == '') {
con.style.display = 'block';
} else {
con.style.display = '';
}
}
它會很好地工作
使用此行代碼:
if(con.style.display == 'none' || con.style.display == '') {
openSearch = () => { var con = document.getElementById("search-bar"); if(con.style.display == 'none' || con.style.display == '') { con.style.display = 'block'; } else { con.style.display = 'none'; } }
#search-bar { position: absolute; height: 4em; width: 20em; background-color: white; border: 1px solid black; padding: 1.5rem; right: 0; display: none; }
<div id="search-bar">My Div</div> <a onclick="openSearch()" href="#">Click</a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.