1

我有一个在悬停按钮时移动框的功能。只要鼠标悬停在按钮上,我希望该功能每秒一遍又一遍地运行。我也尝试过循环,但我无法让它工作。如果您能对此进行调查,我将不胜感激。这是我的代码:

<!DOCTYPE html>
<head>
<style>
#box {
    position: relative;
    top: 20px;
    left: 10px;
    width: 50px;
    height: 50px;   
    background:#333366;
}
</style>

<script>
function Start() {  

setInterval(Move('box'),1000);

}

var value = 0;
function Move(element) {

    value += 50;    
    var box = document.getElementById(element);
    box.style.transition = "left 0.2s ease-in-out 0s";
    box.style.left = value+'px';    

}
</script>
</head>
<body>
<button onmouseover="Start();">Hover to move</button>
<div id="box"></div>
</body>
</html>
4

4 回答 4

1

像这样的东西?

http://jsfiddle.net/blackjim/HwKb3/1/

var value = 0,
    timer,
    btn = document.getElementById('btn');

btn.onmouseover = function(){
    timer = setInterval(function(){
        //    your loop code here
        Move('box');
    }, 1000);
};

btn.onmouseout = function(){
    clearInterval(timer);
}

function Move(element) {

    value += 50;
    var box = document.getElementById(element);
    box.style.transition = "left 0.2s ease-in-out 0s";
    box.style.left = value + 'px';

}

尝试查看 jQuery,它可能会在一开始对您有所帮助。

于 2013-06-19T16:26:51.797 回答
1

用这个:

setInterval(function(){
    Move('box')
},1000);

您必须将一个函数传递给 setInterval。您实际上是在调用 Move 并传递其返回值。

于 2013-06-19T16:19:04.107 回答
0

尝试这个:

var value = 0;
function move(element) {
    value += 50;
    var box = document.getElementById(element);
    box.style.transition = "left 0.2s ease-in-out 0s";
    box.style.left = value+'px';
    // console.log(box);
}

var button = document.getElementById("buttonID");
button.onmouseover = function() {
    this.iid = setInterval(function() {
        move("boxID");
    }, 1000);
};

button.onmouseout = function() {
    this.iid && clearInterval(this.iid);
};
于 2013-06-19T16:56:38.733 回答
0

当这条线

setInterval(Move('box'),1000);

被执行,Move('box')被评估(并被执行),因此,您的参数setInterval是它的返回值,即null

于 2013-06-19T16:21:38.880 回答