1

我有一个被间隔调用的函数。然后我设置了调用函数的间隔。我有一个 mouseleave / mouseenter 事件来分别清除和设置间隔。但是 clearInterval 不起作用,但是内部的匿名函数被调用了:

interval = setInterval(function() { changeBackground(bgs); }, 2000);


    $('section#main').mouseleave(function() {
        clearInterval(interval);
        alert("j");
    });

    $('section#main').mouseenter(function() {
        var interval = setInterval(function() { changeBackground(bgs); }, 2000);
        alert("n");
    });

    function changeBackground(bgs) {
        $('#black').fadeIn(400, 'swing', function () {
            var Url = "url('content/slides/" + bgs[currentBg] + "')";
            $('#container').css('background-image', Url);
        });

        $('#black').fadeOut();

        currentBg++;

        if(currentBg == totalBg) {
            currentBg = 0;
        }
    }
4

1 回答 1

1

尝试这个:

var interval = null;

$('section#main').mouseleave(function() {
    clearInterval(interval);
    alert("j");
});

$('section#main').mouseenter(function() {
    interval = setInterval(function() { changeBackground(bgs); }, 2000);
    alert("n");
});

interval你在里面var'ingmouseenter所以它在里面是未定义的mouseleave

编辑

您修改了代码:

var interval = setInterval(function() { changeBackground(bgs); }, 2000);

$('section#main').mouseleave(function() {
    clearInterval(interval);
    alert("j");
});

$('section#main').mouseenter(function() {
    interval = setInterval(function() { changeBackground(bgs); }, 2000);
    alert("n");
});

function changeBackground(bgs) {
    $('#black').fadeIn(400, 'swing', function () {
        var Url = "url('content/slides/" + bgs[currentBg] + "')";
        $('#container').css('background-image', Url);
    });

    $('#black').fadeOut();

    currentBg++;

    if(currentBg == totalBg) {
        currentBg = 0;
    }
}
于 2013-02-07T15:48:59.003 回答