今天在网上看到的,里面的内容非常多。说下我自己的理解。

  所谓的防抖就是利用延时器来使你的最后一次操作执行。而节流是利用时间差的办法,每一段时间执行一次。下面是我的代码:

这段代码是右侧的小滑块跟随页面一起滑动。

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>为了测试防抖和节流</title>
<link rel="stylesheet" type="text/css" href="css/cssReset.css"/>
<style type="text/css"> .class1{
width: 100px;
height: 200px;
background: #CCCCCC;
}
#box{
width: 50px;
height: 50px;
background: #289A62;
position: absolute;
right: 0;
top: 0;
} </style>
</head>
<body>
<div class="class1">1</div>
<div class="class1">2</div>
<div class="class1">3</div>
<div class="class1">4</div>
<div class="class1">5</div>
<div class="class1">6</div>
<div class="class1">7</div>
<div class="class1">8</div>
<div class="class1">9</div>
<div class="class1">10</div>
<div class="class1">11</div>
<div class="class1">12</div>
<div class="class1">13</div>
<div class="class1">14</div>
<div class="class1">15</div>
<div class="class1">16</div>
<div class="class1">17</div>
<div class="class1">18</div>
<div class="class1">19</div>
<div class="class1">20</div> <div id="box">
返回顶部
</div>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript"> var windows_height = $(window).height();
var scroll_height = $(window).scrollTop();
setTimeout(function(){
$("#box").animate({
"top":(windows_height/2)+ scroll_height-25
},1000)
},100)
var time1 = false; //给延时器命名
$(window).scroll(function(){
if(time1){
clearInterval(time1) }
time1 = setTimeout(function(){
var scroll_height = $(window).scrollTop();
console.log(scroll_height); $("#box").stop();
$("#box").animate({
"top":(windows_height/2)+ scroll_height-25
},1000)
time1 = false;
},500)
})
// $(window).scroll(function(){
// var scroll_height = $(window).scrollTop();
// console.log(scroll_height);
//
// $("#box").stop();
// $("#box").animate({
// "top":(windows_height/2)+ scroll_height-25
// },1000)
// })
</script>
</html>

这里面只有防抖,没有节流,大家注意一下。78——86行是我没有做防抖的样子。大家可以快速的拉动滚动条,看看这两者的区别。我自己觉得还是没有防抖的好看,哈哈。

05-11 14:00