在硬件中,按键等都会有抖动现象,如何消除抖动,不重复触发事件呢,这就要用到消抖机制了.
这是我用jQuery模拟硬件消抖原理,额,可能是吧...又不对的地方,希望有高手指点指点.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
<!DOCTYPE html> <html> <head> <meta charset= "utf-8" >
<meta http-equiv= "X-UA-Compatible"
content= "IE=edge" >
<title>ajax消抖Demo</title>
<script type= "text/javascript"
src= "js/jquery-2.0.0.min.js" ></script>
<link rel= "stylesheet"
type= "text/css"
href= "css/style.css" >
<script type= "text/javascript" >
$( function () {
var
i = 1; // 计时器计时次数
var
firstClick = true ;
var
_interval;
$( "input" ).click( function (){ // 模拟按键抖动,假定抖动延迟为1s.则1s内所有按键都判定为一次按键请求
if
(i != 1) {
firstClick = false ;
} else {
firstClick = true ;
}
_interval = setInterval(myTimer, 200); // 计时开始
if
(firstClick) { // 按键未抖动,ajax执行
$( this ).val( "ajax中,请骚等..." )
// 模拟ajax网络延时,假设为4s,延时过程中,用户不能再次发起ajax请求
var
test = setTimeout( function (){
myAjax()
},4000);
} else { // 按键抖动中,取消ajax
//$(".msgBtn").css(‘display‘, ‘block‘);
alert( "111" );
return
;
};
});
function
myAjax() {
$( ".msg" ).css({
height: ‘160px‘
});
$( ".msg" ).load( "test.html" , function () {
$( "input" ).val( "ajax done!" );
});
// ajax success
}
// 计时器
function
myTimer() {
i++;
if
(i > 5)
{
i = 1;
$( ".msgBtn" ).css( ‘display‘ , ‘none‘ );
clearInterval(_interval);
}
}
});
</script>
</head> <body style= "text-align:center;" >
<input type= "button"
value= "ajax"
/>
<div class = "msgBtn"
style= "display:none" >上次按键抖动中...</div>
<div class = "msg" >userInfo</div>
</body> </html> |
这是ajax请求test.html文件:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <link rel="stylesheet" href=""> </head> <body> <h3 align="left">userInfo:</h3> <table id="teble1" border="1" cellspacing="0" cellpadding="0" align="center"> <tr> <td width="100px">Name:</td> <td width="100px">cxs</td> </tr> <tr> <td width="100px">Sex:</td> <td width="100px">boy</td> </tr> <tr> <td width="100px">Age:</td> <td width="100px">24</td> </tr> </table> </body> </html>
抖动延迟时间可以*设置,抖动过程中用户再次点击的话判定为上一次点击,也就是一段时间内用户所有的点击都判定为一次触发点击事件.