Dun*_*nno 4 html javascript css
我要做的是让4个可扩展的div相互重叠,转换设置为css为0.6s.因为扩展持续0.6秒我想扩展div在它完成崩溃后失去它更高的z-index,否则它看起来很傻.但是,它不起作用,z-index保持不变.这可能是愚蠢的事,但我找不到它.谢谢!
<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>
Run Code Online (Sandbox Code Playgroud)
小智 6
而不是在代码中找到错误,或许讨论如何自己找到它会很有用.第一步是打开你的devtools窗口(F12)并打开控制台(按下看起来像一个大于标志的小图标,右边有三个水平条).运行程序时,您可能会看到以下内容:
TypeError: Cannot set property 'zIndex' of undefined
Run Code Online (Sandbox Code Playgroud)
调试器将停在该行
setTimeout(function() {this.style.zIndex='0';},600);
Run Code Online (Sandbox Code Playgroud)
嗯.显然this.style是未定义的.怎么会这样?进入控制台(在发生错误的上下文中,换句话说,在传递给setTimeout的函数内)并键入
this.style
Run Code Online (Sandbox Code Playgroud)
事实上你会发现它是未定义的.这是为什么?那是this什么?
this
Run Code Online (Sandbox Code Playgroud)
你会看到类似的东西
Window {top: Window, window: Window, location: Location, ...}
Run Code Online (Sandbox Code Playgroud)
为什么会this是窗口而不是我认为它应该是什么?好吧,this通常设置window为一个没有显式的函数this,如elt.set_style().这就是这里发生的事情.
如何this在系统调用的函数中设置,例如传递给的函数setTimeout?您可以执行@Satpal建议的操作,并将this函数外部的值存储在另一个名称下,例如self,并明确指出.或者,您可以将函数绑定到this,如
function timeout_func(){
this.style.zIndex=0;
}
setTimeout(timeout_func.bind(this));
Run Code Online (Sandbox Code Playgroud)
除了使用控制台查看错误消息并输入要评估的内容之外,您还会发现"范围变量"和"监视表达式"窗口非常有用.
通常,使用devtools可以很容易地解决诸如此类的问题.如果您不知道它是什么,谷歌Chrome devtools(从F12开始).不使用它就像在黑暗中编程一样.