问题描述
|
我很沮丧我想做的是:每当我的鼠标指针进入一个框时,我都希望不断更改框的颜色。但是,当鼠标离开盒子时,我希望盒子的颜色停止变化。我必须承认,我正在学习JS,变量范围给了我很多麻烦。
干得好:
var t = true;
Crafty.addEvent(this,Crafty.stage.elem,\"mousemove\",function(e){
if(e.clientX<294)
{
console.log(\"Left edge\");
while(t==true){do something}
}
else if(e.clientY<10)
{
console.log(\"Top Edge\");
}
else if(Math.abs(e.clientX-1084)<10)
{
console.log(\"Right Edge\");
}
else if(Math.abs(e.clientY-600)<10)
{
// console.log(\"Bottom Edge\");
}
else
{
t = false;
}
});
更清楚地说,我想在鼠标位于盒子外面时执行一个操作(我希望两种情况都是相同的:盒子外面仍然是盒子)。上面的代码进入无限循环。
解决方法
像这样? http://jsfiddle.net/2eWkN/
var box = document.getElementById(\'box\'),changeColor = function() {
var r = ~~(Math.random() * 255),g = ~~(Math.random() * 255),b = ~~(Math.random() * 255);
box.style.backgroundColor = \"rgb(\" + r + \',\' + g + \',\' + b + \')\';
},intvl;
box.onmouseover = function() {
intvl = setInterval( changeColor,50 );
};
box.onmouseout = function() {
clearInterval( intvl );
};