// 节流 在一定时间内,只会执行一次 const btn = document.querySelector('.btn'); const str = document.querySelector('p'); let num = 0; // 使用lodash 方法 btn.addEventListener('click', throttle(fn, 5000)) function throttle(fn, T) { let dowTime = null; return function () { if (!dowTime) { dowTime = setTimeout(function () { fn(); dowTime = null; // 清楚定时器 }, T) } } } function fn() { num++; str.innerHTML = `执行的是第${num}次`; }
时间: 2024-04-27 19:25:27 浏览: 24
这是一个 JavaScript 实现节流的例子。在这个例子中,使用了 Lodash 库提供的 throttle 方法来实现节流功能。当用户点击按钮时,事件处理函数会被触发,但是函数内部的执行逻辑会被节流,即在一定时间间隔内只会执行一次。这个时间间隔由第二个参数 T 来控制,单位是毫秒。在这个例子中,时间间隔被设置为 5000 毫秒,也就是 5 秒钟。每次执行事件处理函数 fn() 时,都会将 num 变量加一,并将其值显示在页面上。通过使用节流功能,可以避免在短时间内多次执行事件处理函数,从而减轻浏览器的负担,提升用户体验。
相关问题
btn: document.querySelectorAll('.box button')和const btn=document.querySelector('.box buttin')一样吗
btn: document.querySelectorAll('.box button') 和 const btn = document.querySelector('.box button') 是不同的。
1. btn: document.querySelectorAll('.box button') 是一个使用 CSS 选择器来获取所有 class 为 'box' 的元素下的所有 button 元素的集合。返回的是一个 NodeList 对象,可以通过索引来访问其中的元素。
2. const btn = document.querySelector('.box button') 是使用 CSS 选择器来获取 class 为 'box' 的元素下的第一个 button 元素。返回的是一个单个元素,可以直接访问该元素的属性和方法。
所以,它们的作用是不同的,前者返回多个元素的集合,后者返回单个元素。
const parts = document.querySelector('.part1') // console.log(parts); const btn = document.querySelector('.btn-inner-btn') const c_tx_highlight = document.querySelector('.comment__tips') const tx = document.querySelector('#tx') tx.addEventListener('focus', function() { c_tx_highlight.style.opacity = 0 })这些代码什么意思
这段代码使用了querySelector方法来选择页面中的元素。通过使用'.part1'类名,选择了class为part1的元素。同样,使用'.btn-inner-btn'类名和'.comment__tips'类名来选择对应的元素。在最后使用了querySelector方法来选择第一个匹配' '空格的元素。这些元素将被存储在变量parts、btn、c_tx_highlight和tx中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)