我制作了一个页面,用户可以通过将颜色输入文本框来更改页面的正文/页眉/页脚的背景颜色。我的功能是:function changebody(){ let color = document.getElementById("bodycolor").value; document.body.style.backgroundColor = color;}function changenav(){ let color = document.getElementById("navcolor").value; document.getElementsByTagName("nav").style.backgroundColor=color;}function changefoot(){ let color = document.getElementById("footcolor").value; document.getElementsByTagName("footer").style.backgroundColor = color;}身体的功能工作正常,但我似乎无法让页脚和导航栏的功能工作。有什么建议吗?(我已经检查过我是否得到了正确的ID。编辑:感谢您的评论!!它现在:D
2 回答
倚天杖
TA贡献1828条经验 获得超3个赞
你差不多明白了,请更改这些行:
document.getElementsByTagName("nav")[0].style.backgroundColor=color;
document.getElementsByTagName("footer")[0].style.backgroundColor = color;
这样做的原因是返回值就像一个数组。getElementsByTagName()
杨__羊羊
TA贡献1943条经验 获得超7个赞
我希望你做得很好。
因此,getElementsByTagName() 方法接受一个标记名称,并返回具有匹配标记名称的元素的实时 HTMLCect,这些元素按它们在文档中出现的顺序排列。HTML 集合是一个类似数组的对象。
现在,在这种情况下,将只有一个元素,即索引为0的第一个元素。
因此,您必须使用以下行:
document.getElementsByTagName("nav")[0].style.backgroundColor=color;
document.getElementsByTagName("footer")[0].style.backgroundColor = color;
添加回答
举报
0/150
提交
取消