[英]Set z-index with javascript setTimeout()
我想做的是讓4個可擴展的div相互重疊,並在CSS中設置0.6s的過渡。 因為擴展持續時間為0.6s,所以我希望擴展后的div崩潰后會丟失較高的z-index,否則它看起來很愚蠢。 但是,它不起作用,z索引保持不變。 這可能有點愚蠢,但是我找不到它。 謝謝!
<div class="wrapper" style="position: relative;">
<div id="one" style="position: absolute;" onmouseover="
this.style.height='250px';
this.style.zIndex='1';
" onmouseout="
this.style.height='50px';
setTimeout(function() {this.style.zIndex='0';},600);
">blahblahblahblah</div>
<div id="two" style="position: absolute;" onmouseover="
this.style.height='250px';
this.style.zIndex='1';
" onmouseout="
this.style.height='50px';
setTimeout(function() {this.style.zIndex='0';},600);
">blahblahblahblah</div>
</div>
與其找到代碼中的錯誤,不如討論自己如何找到它,可能會很有用。 第一步是打開devtools窗口(F12)並打開控制台(按看起來像一個大於號的小圖標,並在右邊帶三個水平條)。 運行程序時,您可能會看到以下內容:
TypeError: Cannot set property 'zIndex' of undefined
調試器將在該行停止
setTimeout(function() {this.style.zIndex='0';},600);
嗯 顯然, this.style
是未定義的。 怎么可能 進入控制台(在發生錯誤的上下文中,換句話說,在傳遞給setTimeout的函數內部)並鍵入
this.style
實際上,您會看到它是未定義的。 這是為什么? 那么,什么是this
?
this
你會看到類似
Window {top: Window, window: Window, location: Location, ...}
為什么this
是窗口,而不是我認為的窗口? 好吧,通常this
設置為不帶顯式this
的函數的window
,如elt.set_style()
。 這就是這里發生的事情。
如何在系統調用的函數(例如傳遞給setTimeout
的函數)中設置this
函數? 你可以做什么@Satpal建議,並存儲的值this
另一個名字外的功能,如self
,並明確提到這一點。 或者,您可以將函數綁定到this
,如
function timeout_func(){
this.style.zIndex=0;
}
setTimeout(timeout_func.bind(this));
除了使用控制台查看錯誤消息並輸入要評估的內容外,您還將發現“作用域變量”和“監視表達式”窗口非常有用。
通常,使用devtools可以輕松解決此類問題。 如果您不知道它是什么,請使用Google Chrome devtools(首先按F12鍵)。 實際上,不使用它就像在黑暗中編程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.