我在窗口调整大小时像这样调用一个函数:
window.addEventListener("resize", calculateDimensions());
但我需要在窗口大小调整后调用不同的函数。 有没有使用本机JS(而不是jquery)实现这一点的方法?
TIA
我在窗口调整大小时像这样调用一个函数:
window.addEventListener("resize", calculateDimensions());
但我需要在窗口大小调整后调用不同的函数。 有没有使用本机JS(而不是jquery)实现这一点的方法?
TIA
function debounce(func){
var timer;
return function(event){
if(timer) clearTimeout(timer);
timer = setTimeout(func,100,event);
};
}
可以像这样使用:
window.addEventListener("resize",debounce(function(e){
alert("end of resizing");
}));
我喜欢Jonas Wilms巧妙的防抖函数,但我认为将防抖时间作为参数传递会更好。
// Debounce
function debounce(func, time){
var time = time || 100; // 100 by default if no param
var timer;
return function(event){
if(timer) clearTimeout(timer);
timer = setTimeout(func, time, event);
};
}
// Function with stuff to execute
function resizeContent() {
// Do loads of stuff once window has resized
console.log('resized');
}
// Eventlistener
window.addEventListener("resize", debounce( resizeContent, 150 ));
function debounce(func, time = 100){
。 - ACJ使用 npm 的 debounce
包:
npm i debounce
const debounce = require('debounce');
window.onresize = debounce(resize, 200);
function resize(e) {
console.log('height', window.innerHeight);
console.log('width', window.innerWidth);
}
使用 window.addEventListener("resize", calculateDimensions);
calculateDimensions()
意味着你执行该函数,然后将其结果用作回调函数。