我对JS很陌生。以下JS代码在页面加载时无法工作。
function alert10() {
var today = new Date().getMinutes();
if (today > 10) {
window.onload = function() {
document.getElementById('timer10').style.display = 'none';
};
}
}
我按如下方式调用alert10():
<header onload="alert10()">
下面是我试图隐藏的元素:
<h5 id="timer10" style=" position:absolute;top: 1px;left: 151px;"></h5>
发布于 2019-11-09 16:04:04
使用window.onload尝试以下操作
<html>
<body>
<h5 id="timer10" style=" position:absolute;top: 1px;left: 151px;">Something</h5>
<script>
window.onload = () => {
var today = new Date().getMinutes();
if (today > 10) {
document.getElementById('timer10').style.display = 'none';
} else {
alert('minutes is less than 10')
}
}
</script>
</body>
</html>
发布于 2019-11-09 16:20:24
执行报头onload函数时,窗口onload可能已经触发。如果将窗口侦听器从函数中取出,则计时器将按预期的方式隐藏(如果自上个小时开始以来已经过去了10分钟)。如果您使用例如单击监听器或任何其他后续触发器,它也同样有效。
window.onload = function() {
document.getElementById('timer11').style.display = 'none';
};
function alert10() {
var today = new Date().getMinutes();
if (today > 10) {
document.getElementById('timer10').style.display = 'none';
} else {
console.log("10 minutes haven't past since last hour started")
}
}
我增加了第二个计时器来显示
<header onload="alert10()" onclick="alert10()">
<h5 id="timer10" style=" position:absolute;top: 1px;left: 151px;">timer10</h5>
<h5 id="timer11" style=" position:absolute;top: 1px;left: 251px;">timer11</h5>
</header>
和一点css,使可点击区域变得明显。
header {
position: relative;
width: 100%;
height: 20vh;
background-color: mediumseagreen;
}
https://stackoverflow.com/questions/58780832
复制相似问题