2011-11-27 72 views
0

简单的jQuery,当用户正在键入时,将类.typing添加到<html>标记中。我尝试了几种不同的东西,都没有工作,不知道如何做到这一点。jQuery脚本

$('html').keypress(function(){ 
    $(this).addClass('typing'); 

    if (/* No key is pressed again in the next 0.5 seconds */) { 
     $('.typing').removeClass('typing'); 
    } 
}); 
+1

最新问题? – ManseUK

+0

请详细说明你实际上在问什么 - 是关于在if之后实现条件还是为什么这个脚本不适合你(document.ready stuff等)? – alonisser

+0

以下答案已经修复此问题 –

回答

5

创建其中0.5秒之后执行特定代码的功能,使用setTimeout(与clearTimeout结合,以防止从被同时启动多个超时)。

var timer;     //Local variable to hold time-out reference 
function refreshPress(){ 
    clearTimeout(timer); //Prevent stacked time-outs, only one is allowed 
    timer = setTimeout(function(){ 
     $('.typing').removeClass('typing'); 
    }, 500); //0.5 seconds 
} 

$('html').keypress(function(){ 
    $(this).addClass('typing'); //This line can also be merged with refreshPress 
    refreshPress();    // Call refreshPress 
}); 
+0

感谢您的快速回复!真棒 –

+0

实际上,现在我试了一下,打了几次后,停止使用延迟,并立即添加并删除它 –

+0

@JamesKyle显示你的代码的小提琴。你有没有在答案中正确实施代码? –

1

使用setTimeout()和clearTimeout()代替if。