gpt4 book ai didi

javascript - 为什么是 "load event not working on addEventListener()"?

转载 作者:行者123 更新时间:2023-11-30 10:58:58 24 4
gpt4 key购买 nike

我试图在加载页面的正文元素后记录一些内容,但日志没有出现在控制台中。我究竟做错了什么?

const body = document.querySelector('body');

function setInitialGradient() {
console.log('Cant see this message on console');
body.style.background = `linear-gradient(to right, ${color1.value}, ${color2.value})`;
cssProperty.textContent = body.style.background + ';';
}

body.addEventListener('load', setInitialGradient);

最佳答案

改用 DOMContentLoaded

DOMContentLoaded事件将更早触发,通常被认为是更好的选择。

[the load event] should be used only to detect a fully-loaded page. It is a common mistake to use load where DOMContentLoaded would be more appropriate.

在文档对象上设置它。

document.addEventListener('DOMContentLoaded', setInitialGradient);

如果一定要使用load事件

如果您必须使用 load事件,您可以改为向 window 添加一个监听器:

window.addEventListener('load', setInitialGradient);

但注意:

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

关于javascript - 为什么是 "load event not working on addEventListener()"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58730444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com