原生 resize 事件只掛在 window 上,元素本身的尺寸變化無法監聽——這是前端開發常見的痛點,尤其在做自適應圖表、畫布重繪時特別麻煩。以下這段社群流傳的腳本,用輪詢的方式為任意元素補上了 resize 事件。
// resize of div
(function($, h, c) {
var a = $([]),
e = $.resize = $.extend($.resize, {}),
i,
k = "setTimeout",
j = "resize",
d = j + "-special-event",
b = "delay",
f = "throttleWindow";
e[b] = 250; // 輪詢間隔(毫秒)
e[f] = true; // 是否節流 window resize
$.event.special[j] = {
setup: function() {
if (!e[f] && this[k]) { return false; }
var l = $(this);
a = a.add(l);
$.data(this, d, { w: l.width(), h: l.height() }); // 記錄初始尺寸
if (a.length === 1) { g(); } // 只有第一個元素時啟動輪詢
},
teardown: function() {
if (!e[f] && this[k]) { return false; }
var l = $(this);
a = a.not(l);
l.removeData(d);
if (!a.length) { clearTimeout(i); } // 全部解除後停止輪詢
},
add: function(l) {
if (!e[f] && this[k]) { return false; }
var n;
function m(s, o, p) {
var q = $(this),
r = $.data(this, d);
r.w = o !== c ? o : q.width();
r.h = p !== c ? p : q.height();
n.apply(this, arguments);
}
if ($.isFunction(l)) { n = l; return m; }
else { n = l.handler; l.handler = m; }
}
};
function g() {
i = h[k](function() {
a.each(function() {
var n = $(this),
m = n.width(),
l = n.height(),
o = $.data(this, d);
if (m !== o.w || l !== o.h) { // 尺寸有變才觸發
n.trigger(j, [o.w = m, o.h = l]); // 把新舊尺寸當參數傳出去
}
});
g(); // 遞迴排下一次輪詢
}, e[b]);
}
})(jQuery, this);
$('div').resize(function(){
// 尺寸變化時要做的事
});
// 也能拿到新尺寸
$('div').resize(function(event, oldW, oldH){
console.log('寬:' + $(this).width() + ',原為 ' + oldW);
});
核心概念很單純:用 setTimeout 做週期性輪詢,比對目前尺寸與上次記錄的尺寸。變化了就 trigger('resize'),並把舊的寬高當參數傳給回呼函式。幾個設計細節值得注意:
a 裡,只啟動一個計時器(a.length === 1 時才呼叫 g()),避免多元素時產生多條輪詢。teardown 會把元素移出陣列,全部解除後 clearTimeout 停止輪詢,不留計時器洩漏。$.resize.delay = 250 控制輪詢頻率;數值越小越即時,但 CPU 消耗越高。輪詢始終是權宜之計。目前瀏覽器已原生支援 ResizeObserver,由瀏覽器在排版後主動通知,效能遠優於定時比對,寫法也更乾淨:
const ro = new ResizeObserver(entries => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
console.log('尺寸變了:', width, height);
}
});
ro.observe(document.querySelector('div'));
新專案請優先採用 ResizeObserver;只有需要支援相當舊的瀏覽器時,才需要回頭使用上面這類輪詢插件。