尝试创建一个“hello world”警报,每当浏览器窗口达到 1200 像素时就会触发该警报。
示例:从 1220 像素滚动到 1100 像素:事件在 1200 处触发一次。 示例:从 1100 像素滚动到 1220 像素:甚至在 1200 像素时触发一次。
如有任何帮助,我们将不胜感激。
这就是我一直在研究的内容(大部分)
window.onresize = function ()
{
if (window.innerWidth = 1199) {
//alert ("The size of the window is 1199");
location.reload();
return;
}
}
这是清理后的代码。 我不认为 == 或 === 在这种情况下会产生影响
window.onresize = function ()
{
if (window.innerWidth === 1199) {
alert ("The size of the window is 1199");
}
}
最佳答案
为了在用户调整大小时可靠地识别达到精确宽度 1199 的窗口,resize
事件不会像您希望的那样频繁触发。
例如
window.onresize = function() { console.log(window.innerWidth); }
查看粒度。
为了解决有损事件通知,您可以检测通过阈值的任何大小调整。这仍然可能会错过阈值附近的一些大小调整,但应该会获取调整大小的聚合变化:
var thresholdWidth = 1199;
var previousWidth = window.innerWidth;
window.onresize = function() {
var movedUpThroughThreshold = previousWidth < thresholdWidth &&
window.innerWidth >= thresholdWidth;
var movedDownThroughThreshold = previousWidth >= thresholdWidth &&
window.innerWidth <= thresholdWidth;
if (movedUpThroughThreshold || movedDownThroughThreshold) {
console.log("passed threshold", previousWidth, "->", window.innerWidth)
}
previousWidth = window.innerWidth;
}
兼容性说明
如果您需要以 IE8 为目标,则需要考虑 innerWidth
的可用性,并且尽管标准将 insideWidth 描述为视口(viewport)宽度(包括滚动条),但各种用户代理中可能存在问题。
如果innerWidth不可用,您可能需要使用documentElement或body作为视口(viewport)的代理,但您需要确保它们填充视口(viewport)但不超过它。
关于javascript - 仅在特定窗口大小下执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34956303/