gpt4 book ai didi

javascript - 如何修复 Javascript 函数的 'Typerror is undefined' 消息?

转载 作者:行者123 更新时间:2023-11-28 13:35:08 26 4
gpt4 key购买 nike

我试图在用户将鼠标悬停在所选选项上时立即操纵背景图像。我在 firebug 中测试了我的代码并加载了页面。我立即得到:

TypeError: document.getElementsByTagName(...).style is undefined

var bg = document.getElementsByTagName("html").style.backgroundColor = "white";

对于悬停我得到:

TypeError: bg.document is undefined

bg.document.getElementsByTagName("html").style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/b/be/500_USD_note%3B_series_of_1934%3B_obverse.jpg')";

如何修复此错误?

HTML 代码:

<form>
<!--show a large print of green font color and size money-->
Select your DSLR budget range:
<select id="budgetSel" onChange="onChange();">
<option value="selectOneBudget" selected="selected">Select one</option>
<option value="fiveHundredDollars" onMouseOver="changeBackgroundImage(this);">&lt; $500</option>
<option value="thousandDollars" onMouseOver="changeBackgroundImage(this);">&lt; $1000</option>
</select>
</form>

CSS 代码:

html{
background: url('http://upload.wikimedia.org/wikipedia/commons/8/8a/1000_USD_note%3B_series_of_1934%3B_obverse.jpg') no-repeat center center fixed;
/*-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;*/
background-size: cover;
min-width:1300px; /*keep the same width when resizing*/
}

JAVASCRIPT:

var bg = document.getElementsByTagName("html").style.backgroundColor = "white";
// function to dynamically change the background image when user hovers over an option in select menu
function changeBackgroundImage(bg)
{
bg.document.getElementsByTagName("html").style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/b/be/500_USD_note%3B_series_of_1934%3B_obverse.jpg')";
}

最佳答案

顾名思义:

document.getElementsByTagName

返回标签的集合而不是单个节点,我说是集合是因为​​它实际上并不返回数组,而是返回类似数组的对象。

如果你只需要获取html节点,你可以简单地这样做:

document.lastChild.style.backgroundColor = "white";

还有

document.documentElement.style.backgroundColor = "white";

但是如果您需要使用类似的查找函数来查找它,您应该这样做:

document.getElementsByTagName("html")[0].style.backgroundColor = "white";

还有这个:

document.querySelector("html").style.backgroundColor = "white";

关于javascript - 如何修复 Javascript 函数的 'Typerror is undefined' 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22118923/

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