[英]Can we distinguish the reason that cause a window.resize event in Chrome?
當觸發下載事件時, Chrome瀏覽器底部會出現下載欄,會觸發window.resize事件。 同樣,如果我們關閉下載欄,也會觸發 window.resize 事件。 能否區分事件是下載欄觸發還是手動觸發? 謝謝!!
您不能 100% 知道導致調整大小的原因,但您可以根據更改的尺寸推斷出它。 這是一個粗略的示例,說明您可能會如何 go :
const state = {
width: window.innerWidth,
height: window.innerHeight
};
const DOWNLOAD_BAR_SIZE = 50;
const TOLERANCE = 0.25;
window.addEventListener("resize", () => {
let type = "resize";
const diffHeight = state.height - window.innerHeight;
const bounds = {
min: diffHeight >= DOWNLOAD_BAR_SIZE * (1 - TOLERANCE),
max: diffHeight <= DOWNLOAD_BAR_SIZE * (1 + TOLERANCE)
};
if (diffHeight >= bounds.min && diffHeight <= bounds.max) {
type = "download";
}
state.width = window.innerWidth;
state.height = window.innerHeight;
console.log(type);
});
這將跟蹤 window 的當前大小,並在未來調整 window 的大小。 當一個下載欄從底部彈出時,高度尺寸將改變~50px。 您可以更改TOLERANCE
和DOWNLOAD_BAR_SIZE
常量以滿足您的需要。
類似的策略可以應用於開發工具。
我認為代碼有一些錯誤,但基礎非常有用。
bounds.min 和 bounds.max 通過與 dffHeight 比較計算為 boolean,然后再次與 diffHeight 比較。
我更喜歡將它們設為數字,以便我可以顯示它們的值。
const state = {
width: window.innerWidth,
height: window.innerHeight
};
const DOWNLOAD_BAR_SIZE = 50;
const TOLERANCE = 0.25;
let type = "resize";
window.addEventListener("resize", () => {
const diffHeight = state.height - window.innerHeight;
const bounds = {
min: DOWNLOAD_BAR_SIZE * (1 - TOLERANCE),
max: DOWNLOAD_BAR_SIZE * (1 + TOLERANCE)
};
console.log( "bounds.min = " + bounds.min + ", bounds.max = " + bounds.max + ", diffHeight = " + diffHeight );
if ( /* diffHeight >= bounds.min && */ diffHeight <= bounds.max) {
type = "download";
} else {
type = "resize";
}
state.width = window.innerWidth;
state.height = window.innerHeight;
console.log(type);
});
我將調整大小類型指示器移出偵聽器,以防我需要在其他地方知道。 此外,我在關閉工具欄時收到多個事件,因此我不再檢查最小值(例如,打開工具欄觸發調整大小為 57 的事件,關閉觸發三個事件 14、20、23)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.