0

考虑我们有一个简单的循环 Javascript 过程:

function test() {
    el=document.getElementById("test");
    var opacity = 1;
    var id = setInterval(function() {
    opacity = opacity - 0.1;
    el.style.opacity= opacity;
    \\ if(mouseout) {clearInterval(id);} How to do this?
    if(opacity == 0) {clearInterval(id);}
    }, 500);
}

document.getElementById("test").
addEventListener('mouseover', function(){
  test();
});

一旦moveover发生事件,该过程就会启动并继续,直到到达if condition. 我们如何定义另一个if condition以通过另一个事件来停止该过程。

在当前示例中,我们如何在mouseout事件发生时停止进程(降低不透明度)。

4

2 回答 2

2

id在函数之外声明你的变量。然后你可以clearInterval(id)从你的mouseout处理程序调用。

请注意,您实际上并不需要该test()函数,您可以将其内容直接放在鼠标悬停处理程序中:

var id,
    el = document.getElementById("test");

el.addEventListener('mouseover', function(){
    var opacity = 1;
    id = setInterval(function() {
       opacity = opacity - 0.1;
       el.style.opacity= opacity;
       if(opacity == 0) {clearInterval(id);}
    }, 500);
});
el.addEventListener('mouseout', function() {
   clearInterval(id);
});
于 2012-06-24T06:50:31.303 回答
2
var el = document.getElementById("test"),
    opacity = 1,
    id;


el.addEventListener('mouseover', function(){
    id = setInterval(function() {
            opacity = opacity - 0.1;
            el.style.opacity= opacity;
            if(opacity == 0) {clearInterval(id);}
    }, 500);
});

el.addEventListener("mouseout", function() {
   clearInterval(id);
});
于 2012-06-24T06:53:33.113 回答