[英]Show/Hide element by ID
function showhide(id) { obj = document.getElementById(id); if (obj.style.display == 'none' || obj.style.display == null) obj.style.display = 'block'; else obj.style.display = 'none'; }
#stuff { display: none; }
<a href="#" onclick="showhide('stuff'); return false;">Click Me</a> <div id="stuff"> secret stuff </div>
這種方法有效,但需要兩次點擊。 它似乎無法檢測到狀態為null
。
顯然,如果我改變條件,它的工作原理:
if (obj.style.display == 'block')
obj.style.display = 'none';
else
obj.style.display = 'block';
我現在的問題是,第一個條件出了什么問題?
如果元素的顯示是由CSS規則指定的,那么您需要獲得它的計算樣式。 如果要替換div上的內聯樣式,那么您正在做的事情會有效。
function showhide (id) { obj = document.getElementById(id); var displayStyle = obj.currentStyle ? obj.currentStyle.display : getComputedStyle(obj, null).display; if (displayStyle == 'none' || displayStyle == null) obj.style.display = 'block'; else obj.style.display = 'none'; }
#stuff { display:none; }
<a href="#" onclick="showhide('stuff'); return false;">Click Me</a> <div id="stuff"> secret stuff </div>
問問自己:在什么時候obj.style.display
永遠是null
? 如果您實際將其記錄到控制台,您將獲得""
。
在你的第一個代碼中, obj.style.display
既不是"none"
也不是""
,所以執行else
case:它將被設置為"none"
。 它已經不顯示,但僅僅是因為CSS規則,而不是元素本身的直接style
屬性。
你的第二個代碼是有效的,因為它暗示""
和"none"
行為方式相同, "block"
行為方式不同,實際上就是這種情況(如果你只使用"none"
和"block"
)。
您可以直接設置元素的display屬性,而不是使用CSS,因此:
<div id="stuff" style="display:none">
secret stuff
</div>
並擺脫
#stuff { display:none; }
然后你的第一個例子(不需要空檢查)將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.