<!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> <input type="text" id="input" oninput="event" /> </body> <script> function debounce(fn, delay) { let timer; return function () { const context = this; const args = arguments; timer && clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; } const event = debounce(on, 2000); </script> </html>让input输入值发生变化时 调用debounce 让它们关联起来
时间: 2024-03-13 21:45:47 浏览: 102
HTML中的<meta>标签的使用详解
5星 · 资源好评率100%
可以将input的oninput事件绑定到一个函数,该函数调用debounce函数并传入需要防抖的函数以及延迟时间。代码如下:
```html
<!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>
<input type="text" id="input" oninput="handleInput()" />
</body>
<script>
function debounce(fn, delay) {
let timer;
return function () {
const context = this;
const args = arguments;
timer && clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
function handleInput() {
// 需要防抖的函数
console.log('input value changed');
}
const event = debounce(handleInput, 2000); // 调用debounce将需要防抖的函数传入并设定延迟时间
document.getElementById('input').oninput = event; // 将防抖后的函数和input的oninput事件关联起来
</script>
</html>
```
阅读全文