我的代码只在setInterval()或settimeout()函数内工作。我不知道如何使用一个基本的javascript函数。我不想使用setInterval函数,时间是0毫秒,这就是为什么我需要在屏幕上显示任何东西之前获得值。帮我一下——没有这些功能怎么让它工作。
JAVASCRIPT
setInterval(function()
{
if (window.matchMedia("(min-width: 215px)").matches)
{
const mainwidth = window.innerWidth * 1.0;
const mainheight = window.innerHeight * 1.0;
document.getElementById("show-logo").style.setProperty('--set-mainwidth', mainwidth + "px");
document.getElementById("show-logo").style.setProperty('--set-mainheight', mainheight + "px");
}
}, 0);
这段代码运行良好,但我不想使用setInterval或setTimeout。所以我尝试了下面的代码,但不工作。我怎么能解决这个问题,使它快速没有设置任何毫秒的时间…?
JAVASCRIPT
var loadcheck = initialload();
function initialload()
{
if (window.matchMedia("(min-width: 215px)").matches)
{
const mainwidth = window.innerWidth * 1.0;
const mainheight = window.innerHeight * 1.0;
document.getElementById("show-logo").style.setProperty('--set-mainwidth', mainwidth + "px");
document.getElementById("show-logo").style.setProperty('--set-mainheight', mainheight + "px");
}
}
在这个例子中,我定义了一个函数updateLogo()
,它执行两个CSS属性/变量的更新。在document
上使用DOMContentLoaded
上的事件侦听器,在window
上使用resize
上的事件侦听器,该函数将被调用。
如果setInterval()
的目的是在调整窗口大小时更新属性,那么使用事件侦听器要好得多。
document.addEventListener('DOMContentLoaded', updateLogo);
window.addEventListener('resize', updateLogo);
function updateLogo() {
if (window.matchMedia("(min-width: 215px)").matches) {
const mainwidth = window.innerWidth * 1.0;
const mainheight = window.innerHeight * 1.0;
document.getElementById("show-logo").style.setProperty('--set-mainwidth', mainwidth + "px");
document.getElementById("show-logo").style.setProperty('--set-mainheight', mainheight + "px");
}
console.log(document.getElementById("show-logo").outerHTML);
}
<div id="show-logo"></div>