0

我試圖在用戶將光標懸停在選定的選項上時處理背景圖像。我在螢火蟲中測試了我的代碼並加載了頁面。瞬間,我得到:如何解決'Typerror未定義'消息的javascript中的函數?

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')"; 
} 

回答

3

顧名思義:

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"; 
+0

我得到一個錯誤'類型錯誤:bg.document是\t \t \t \t undefined'' bg.document.getElementsByTagName(「html」)[0] .style.backgroundImage =「url('http://upload.wikimedia。組織/維基百科/公地/ B /是/ 500_USD_note%3B_series_of_1934%3B_obverse.jpg')「;' – TheAmazingKnight

2

getElementsByTagName()返回匹配元素的數組, 因此您應該在您的情況下使用索引0

應該

document.getElementsByTagName("html")[0].style 

,而不是

document.getElementsByTagName("html").style 
+0

我發現了一個錯誤'類型錯誤:bg.document是undefined' \t \t \t \t'bg.document.getElementsByTagName( 「HTML」)[0] .style.backgroundImage =「URL(的「http: //upload.wikimedia.org/wikipedia/commons/b/be/500_USD_note%3B_series_of_1934%3B_obverse.jpg')「;' – TheAmazingKnight

相關問題