[英]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.