【发布时间】:2021-12-31 08:11:23
【问题描述】:
我已经有 3 段,需要使用 JavaScript 创建第 4 段 已成功创建。
const new_h2 = document.createElement('h2')
并为 h2 分配一个 ID
new_h2.setAttribute('id', 'heading4');
现在我得到了带有 ID 的 h2
const heading4 = document.getElementById('heading4')
当我尝试在 If 语句中使用它时出现问题
window.addEventListener('scroll', function(){
console.log(window.scrollY);
if(window.scrollY >= 400 && window.scrollY < 800){
heading1.style.color = '#cc1'
// console.log('section1 is styled');
}else if(window.scrollY >= 800 && window.scrollY < 1200){
heading2.style.color = '#cc1'
// console.log('section2 is styled');
}else if(window.scrollY >= 1200 && window.scrollY < 1600){
heading3.style.color = '#cc1'
// console.log('section3 is styled');
}else if(window.scrollY >= 1600){
heading4.style.color = '#cc1'
// console.log('section4 is styled');
}else{
heading1.style.color = '#fff'
heading2.style.color = '#fff'
heading3.style.color = '#fff'
heading4.style.color = '#fff'
}
})
日志显示以下错误:
Cannot read properties of null (reading 'style')
我猜这来自heading4.style.color
但我不知道如何处理。
【问题讨论】:
-
创建元素不会自动将其放入文档中。为什么不简单地使用
new_h2?您已经拥有该元素。
标签: javascript createelement setattribute