这个问题,我纠结了一两天,起初,我用的是原生的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>
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了。
明白一个很深刻的道理,要像大婶学习!