在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中不是'==='? –