2012-07-19 82 views
0

我有一个循环遍历表中的行的函数,以便在任何给定的时间只显示一行。JavaScript中的暂停功能

我想对此进行扩展,以便当我将鼠标悬停在表上时,它会显示所有行,然后当我移开时,它将一次显示一行。

我遇到的问题是悬停时,第一个函数继续前进,有没有办法'暂停'该函数。我使用ClearInterval()查看了各种示例,但无法将它们与我的脚本相匹配。

//Calling The function that loops through the rows  
function hideShow(time) 
{ 
    setInterval('showRows()',time); 
};  

//Set the time between each 'loop' and start looping 
$(document).ready(function() 
{ 
    hideShow(2000); 
} 
); 

//The hover function to show/hide all the rows 
$(document).ready(function() 
{ 
    $('#dbTable1 tr').hover(function() 
     { 
      $('.Group td').removeClass('RoundBottom'); 
      $('.Group').show(); 
     }, 
     function() 
     { 
      $('.Group td').addClass('RoundBottom'); 
      $('.Group').hide(); 
     } 
    ); 
} 
); 

任何人都可以告诉我,我怎么能结合这两个?

回答

1

你需要跟踪定时器ID,当你调用setInterval

var timerID; 

function hideShow(time){ 
    timerID = setInterval(showRows, time); 
} 

再后来,当你想停止重复,调用clearInterval并传入ID上:

// ... 
    $('.Group td').removeClass('RoundBottom'); 
    $('.Group').show(); 
    clearInterval(timerID); 
}, 
function() 
{ 
    hideShow(2000); 
    $('.Group td').addClass('RoundBottom'); 
    // ... 
+0

干杯,我很亲密,但不是那里。这很好。 – IGGt 2012-07-20 15:32:09

0

您可以在做任何其他事情之前检查悬停状态,如下所示:

function showRows() { 
    if (isHovering) { 
     return; 
    } 

    // ... 
} 

isHovering变量只是一个具有当前悬停状态的布尔值,可以由您的回调函数设置。

通过上述方法,您可以只设置一次计时器并忘记它。

+0

为此欢呼。我需要玩一下它。 – IGGt 2012-07-20 15:37:46