--- title: resize slug: Web/API/Window/resize_event translation_of: Web/API/Window/resize_event ---
文档视图调整大小时会触发 resize 事件。
| Property | Type | Description |
|---|---|---|
target {{readonlyInline}} |
EventTarget |
The event target (the topmost target in the DOM tree). |
type {{readonlyInline}} |
DOMString |
The type of event. |
bubbles {{readonlyInline}} |
Boolean |
Whether the event normally bubbles or not. |
cancelable {{readonlyInline}} |
Boolean |
Whether the event is cancellable or not. |
view {{readonlyInline}} |
WindowProxy |
document.defaultView (window of the document) |
detail {{readonlyInline}} |
long (float) |
0. |
由于resize事件可以以较高的速率触发, 因此事件处理程序不应该执行计算开销很大的操作 (如 DOM 修改)。相反, 建议使用requestAnimationFrame, setTimeout or customEvent, 比如:
;(function() {
var throttle = function(type, name, obj) {
obj = obj || window;
var running = false;
var func = function() {
if (running) { return; }
running = true;
requestAnimationFrame(function() {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
obj.addEventListener(type, func);
};
/* init - you can init any event */
throttle("resize", "optimizedResize");
})();
// handle event
window.addEventListener("optimizedResize", function() {
console.log("Resource conscious resize callback!");
});
var optimizedResize = (function() {
var callbacks = [],
running = false;
// fired on resize event
function resize() {
if (!running) {
running = true;
if (window.requestAnimationFrame) {
window.requestAnimationFrame(runCallbacks);
} else {
setTimeout(runCallbacks, 66);
}
}
}
// run the actual callbacks
function runCallbacks() {
callbacks.forEach(function(callback) {
callback();
});
running = false;
}
// adds callback to loop
function addCallback(callback) {
if (callback) {
callbacks.push(callback);
}
}
return {
// public method to add additional callback
add: function(callback) {
if (!callbacks.length) {
window.addEventListener('resize', resize);
}
addCallback(callback);
}
}
}());
// start process
optimizedResize.add(function() {
console.log('Resource conscious resize callback!')
});
(function() {
window.addEventListener("resize", resizeThrottler, false);
var resizeTimeout;
function resizeThrottler() {
// ignore resize events as long as an actualResizeHandler execution is in the queue
if ( !resizeTimeout ) {
resizeTimeout = setTimeout(function() {
resizeTimeout = null;
actualResizeHandler();
// The actualResizeHandler will execute at a rate of 15fps
}, 66);
}
}
function actualResizeHandler() {
// handle the resize event
...
}
}());