首先我们从最上面快速往下滑,在鼠标移入事件里面输出一下index
enters(index) {
this.currentIndex=index;
console.log(index);
}
这样就只会打印这几个
产生原因:这是因为太快了,浏览器还没反应过来。
先了解防抖和节流:
简单理解:节流相当于技能cd,防抖相当于回城。
(1)实现防抖
首先来看一个代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>防抖</title>
</head>
<body>
<p>
请你输入搜索的内容:<input type="text">
</p>
</body>
<script>
let input = document.querySelector('input');
input.oninput = function() {
console.log('ajax发请求');
}
</script>
</html>
我想输入完之后再发送ajax请求,可以采用闭包+定时器,也可以采用Lodash来实现,第一种方法之前已经说过了,见博文:JS淘宝搜索框防抖策略_吃鱼丸的申申的博客-CSDN博客_搜索框 防抖,那么就来看看第二种如何做。安装见官网:Lodash 简介 | Lodash 中文文档 | Lodash 中文网 (lodashjs.com)
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>防抖</title>
<!-- 引入Lodash -->
<script src="./lodash.js"></script>
</head>
<body>
<p>
请你输入搜索的内容:<input type="text">
</p>
</body>
<script>
let input = document.querySelector('input');
// lodash插件:里面封装函数的防抖与节流的业务【闭包+延时器】
// lodash对外暴露_
// _有一个防抖函数debounce 第一个参数是函数,第二个参数是延时毫秒数
input.oninput = _.debounce(function() {
console.log('ajax发请求');
}, 1000);
</script>
</html>
(2)实现节流
扫描二维码关注公众号,回复:
15119622 查看本文章
直接看代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>节流</title>
<script src="./lodash.js"></script>
</head>
<body>
<div>
<h1>我是计数器<span>0</span></h1>
<button>点击我+1</button>
</div>
</body>
<script>
// 获取节点
let span = document.querySelector('span');
let button = document.querySelector('button');
let count = 0;
// 现在要求,在一秒以内,数字只能+1
button.onclick = _.throttle(function() {
count++;
span.innerHTML = count;
}, 1000)
</script>
</html>
总结: