[英]Do something ONLY ONCE if screen width is less than ...px
我只想使用我的功能一次。 不是每次我调整大小。
你认为这可能吗?
window.addEventListener("resize", function() {
const html = document.querySelector(".js-nav");
if (window.matchMedia("(min-width: 1069px)").matches) {
html.style.transform = "translateX(0px)";
} else {
html.style.transform = "translateX(300px)";
}
})
这是我的代码自动取款机,每次我调整大小时它都会进行 translateX 并且只有在我在大于或小于 1069px 的屏幕之间切换时才会发生(因为我也用按钮更改了 translateX,否则当我再次调整大小时它会变得一团糟)。
您可以使用变量来查看该函数是否已被执行,例如:
var wasResized = false;
window.addEventListener("resize", function() {
if (!wasResized) {
const html = document.querySelector(".js-nav");
if (window.matchMedia("(min-width: 1069px)").matches) {
html.style.transform = "translateX(0px)";
} else {
html.style.transform = "translateX(300px)";
}
wasResized = true;
}
})
以较大的页面格式打开 snippit Expand snippit
下方的Expand snippit
按钮并调整浏览器的大小,使 snippit 页面小于 1069px 宽度,然后调整浏览器的大小,并在满足条件时查看事件仅触发一次。 每次调整浏览器大小时,控制台都会在事件触发时显示当前 window.innerWidth。
将条件与计数器一起使用,并将条件设置为仅在计数器设置为0
时触发。
// this is for display purposes only let fired = document.getElementById('fired'); // below is a working example of this same method using a counter set to zero // when the event listener fires, it runs the function and checks to see if the // counter is set to zero, if it is run the code and add one to the counter // affectively making the event listener inactive as the function will no longer run // the conditional as it is not matching the condition required to fire any longer let btn = document.querySelector('button'); let x = 0; window.addEventListener("resize", function() { if (window.matchMedia("(min-width: 1069px)").matches && x === 0) { x++; // run your code you only want to run once here fired.textContent = "The event has fired " + x + " time @ " + window.innerWidth + " inner.width"; console.log("counter: " + x,' min-width matches: 1069px') } else { // run other code that will not fit into your conditionals params here console.log("counter: " + x," => Windows inner width: " + window.innerWidth) } })
<div id="fired"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.