您的位置:首页 > Web前端 > JQuery

javascript && jquery 延时屏幕滚动元素fadeout效果,允许打断。

2015-03-10 11:29 363 查看
这个问题,我纠结了一两天,起初,我用的是原生的javascript代码(原谅我没保留代码),写完之后发现乍一看没问题,但是当快速滚动时,即多次调用了,这个时候必须把之前的函数animation 给clear掉。而延时,之前省事,就用delay方法(jquery方法),后来发现不停快速滚动的时候还是有BUG。百思不得其解,animation动画已经clear了,怎么还会有BUG(快速滚动一闪一闪)?code如下:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>导航条</title>
<style>
body{
padding:0;
margin:0;
}
#nav{
width:100%;
min-height: 45px;
background: #337ab7;
position: fixed;
}

</style>
</head>
<body style="height:2000px;">
<nav id="nav">菜单栏</nav>
<script src="jquery-1.11.2.min.js" type="text/javascript"></script>
<script>
$(function () {
$('body').on('<span style="font-family: Arial, Helvetica, sans-serif;">scroll</span>', function(event) {

$("#nav").stop(true,true).show();
$("#nav").delay(2000).fadeOut(1000,function(){

});
});
});
</script>
</body>
</html>


鼠标不停的滚动(间隔小于2S)就会发现bug,后来,经过大婶提点,原来,不仅仅fadeout 等animation放入了队列,delay也是有可能放入了队列的,于是乎,在jquery官网上查询一番,果不其然:
Description: Set a timer to delay execution of subsequent items in the queue.


然而,怎么clear队列呢?往下看,有新发现:

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.


原来clear不掉,但是没关系,可以用原生的settimeout来作延时器:

$(function(){
var timer = null;

var timerStart = function(){
window.clearTimeout(timer);
timer = null;
$('#nav').show();
timer = window.setTimeout(function(){
$('#nav').fadeOut();
}, 2000);
}

$(window).on('scroll', function(event) {
timerStart();
});
});


至此,大功告成,不再有BUG了。

明白一个很深刻的道理,要像大婶学习!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: