【发布时间】:2020-04-17 21:48:08
【问题描述】:
如果这听起来很愚蠢,我很抱歉,但是在 3 小时试图找到答案后,我不知所措。我刚开始为一个大学项目学习 Javascript。
所以我尝试使用 Javascript 动态更改页面中某些元素的颜色,虽然这适用于页脚等唯一元素,但我在元素中收到“未捕获的类型错误:无法读取未定义的属性‘样式’”例如 p 或 h4。我遵循了我在这个线程上读到的内容:How to set the color of H1 using javascript? 但我仍然收到错误消息。这是我的代码:
const lightButton = document.getElementById("lighting_button");
console.log(lightButton);
const paragraph = document.querySelectorAll("p");
//console.log(p);
//console.log(contentHeader);
const bodyOfFile = document.body;
lightButton.addEventListener('click', (e) => {
if(lightButton.textContent === "Dark Mode"){
document.body.style.backgroundColor = "#1a1a1a";
document.querySelector('#footer').style.color = "#e6e6e6";
const contentHeader = document.querySelectorAll("h4");
for(let j=0; contentHeader.length-1; j++){
contentHeader[j].style.color = "#ffffff";
}
for(let i=0; paragraph.length-1; i++){
paragraph[i].style.color = "#e6e6e6";
}
}
});
最奇怪的是,即使出现错误,它也确实使我的 h4 变白。 任何帮助将不胜感激。
【问题讨论】:
标签: javascript css dom-events