在comment你說,這刷新後調整大小正常。爲了達到這個目的,你需要一個去抖動器。 Debouncer是一個函數,它檢查一個事件是否在給定的延遲後未被觸發,然後纔會觸發事件處理程序。像這樣:
var oldSide = window.innerWidth - 1200; // Stores positive value, if current size is greater than 1200, else zero or negative
// This is the debouncer, it delays the execution of the given handler untill user stops resizing
function debounce(fn, delay) {
var delayId, delay = delay || 200;
return function() {
var scope = this, args = arguments;
clearTimeout(delayId);
delayId = setTimeout(function() {
fn.apply(scope, Array.prototype.slice.call(args));
}, delay);
}
}
// Here we add the resize listener, notice, that we call the debouncer, and pass our actual handler to that
$(window).resize(debounce(function (e) {
var newSide = window.innerWidth - 1200;
// newSide * oldSide is negative, if 1200 is acrossed in either directions during the last resizing
if (newSide * oldSide <= 0) {
// Window size acrossed 1200 during the last resize, refresh the page
}
// Window size didn't across 1200 during the last resize, set a new value to oldSide, and keep listening
oldSide = newSide;
}));
A working demo at jsFiddle(僅記錄到控制檯,不刷新)。
請注意,如果在1200超過時不打算實際刷新,則必須從if
塊返回。
你也可以在去抖動器(在clearTimeout
之後)檢測到「跨越邊界」,這樣它會更加實時,但可能有幾個像素的間隙。
我在這裏使用的去抖動器起源於BGerrissen's great answer at SO。
'window.innerWidth'是隻讀的......修正之後,很可能在您讀取該值時,它不是1199.您需要一個空白。 – Teemu
在if語句中使用'==' – rosscj2533
@ rosscj2533其實,在javascript中不是'==='? –