1

我难住了。我想要做的是:每当我的鼠标指针进入一个盒子时,我想不断改变盒子的颜色。但是,当鼠标离开框时,我希望框的颜色停止变化。我必须承认我正在学习 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;
    }




});

更清楚地说,我想在鼠标在盒子外面时执行操作(我希望两种情况是等价的:盒子外面仍然是盒子)。上面的代码进入无限循环。

4

1 回答 1

4

像这样?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 );
};
于 2011-06-14T21:07:41.800 回答