我写了一个demo,其功能是鼠标移入时长方形块长度变长,然后高度变高,遇到如下问题:
在执行下面这段函数嵌套时
oDiv[0].onmouseover = function(){
that = this;
changeStyle(that,'width',400,function(){
changeStyle(that,'height',300);
});
}
必须使用that=this传参,否则浏览器会报如下错误
Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
我在最后贴出了整套代码,我想知道为什么用that=this传参能解决问题?不传参的话this两次分别指向了谁?chrome和firefox有没有什么好的调试方法能监视每一次this值的变化并显示出来?
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>animation</title>
<link rel="stylesheet" href="animation.css" />
</head>
<body>
<div class="wrap"></div>
<script src="animation.js"></script>
</body>
</html>
css代码:
.wrap{
width: 200px;
height: 100px;
margin: 10px;
background-color: #f00;
border: 4px solid black;
}
js代码:
window.onload = function(){
var oDiv = document.getElementsByTagName('div');
oDiv[0].timer = null;
oDiv[0].onmouseover = function(){
that = this;
changeStyle(that,'width',400,function(){
changeStyle(that,'height',300);
});
}
}
function changeStyle(obj,attr,iTarget,fn){
clearInterval(obj.timer);
var curValue = 0;
obj.timer = setInterval(function(){
curValue = parseInt(getStyle(obj,attr));
var speed = (iTarget - curValue) / 20;
speed = (speed > 0) ? Math.ceil(speed) : Math.floor(speed);
if (curValue == iTarget) {
clearInterval(obj.timer);
if (fn) {
fn();
}
}
else{
obj.style[attr] = curValue + speed + 'px';
}
},30);
}
function getStyle(obj,attr){
if (obj.currentStyle) {
return obj.currentStyle[attr];
}
else{
return getComputedStyle(obj,null)[attr];
}
}
通过事件调用的函数的this指向触发该事件的元素,所以oDiv[0].onmouseover事件调用函数的this指向的是oDiv[0];
changeStyle函数传入的回调函数的this指向的是window,因为 if (fn) { fn();}相当于window调用了该函数
如果想跟踪代码的执行情况可以采用断点调试,能看到各个变量在运行中的赋值情况