Javascript 在 window 调整大小结束
Javascript on window resize end
当 window 像这样调整大小时,我正在调用一个函数:
window.addEventListener("resize", calculateDimensions());
但是我需要一种方法来在 window 调整大小后调用不同的函数。
有什么方法可以使用原生 js 实现这一点(不是 jquery)
TIA
使用window.addEventListener("resize", calculateDimensions);
calculateDimensions()
表示您执行该函数,然后将该结果用作回调函数。
您可以设置超时并在再次触发调整大小时重置它。所以上次超时没有取消,函数是运行:
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 ));
使用 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 像这样调整大小时,我正在调用一个函数:
window.addEventListener("resize", calculateDimensions());
但是我需要一种方法来在 window 调整大小后调用不同的函数。 有什么方法可以使用原生 js 实现这一点(不是 jquery)
TIA
使用window.addEventListener("resize", calculateDimensions);
calculateDimensions()
表示您执行该函数,然后将该结果用作回调函数。
您可以设置超时并在再次触发调整大小时重置它。所以上次超时没有取消,函数是运行:
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 ));
使用 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);
}