2015-05-28 85 views
0
  • 會有什麼語法使用JavaScript
  • 改變身體的背景圖像如何修復線錯誤動態地改變一個div的背景圖像y.style.background = '' + "url(1.jpg) no-repeat" + '';

標記:如何使用純JavaScript

<!DOCTYPE html> 
<html> 

<head> 
    <style> 
     body { 
      //this is the style for body tag 
      background: url("heart.png") no-repeat; 
      color: red; 
     } 
    </style> 
</head> 

<body> 
    <h3><p id="hello">This Is Heart.</p> 
     </h3> 
    <button onclick="myFunction()">Try it</button> 
    <script> 
     function myFunction() { 
       var x = document.getElementById("hello"); //this is id of paragraph 
       var y = document.getElementsByTagName("body"); //id of background element 
       var z = document.getElementById('myImg'); 
       y.style.background = '' + "url(1.jpg) no-repeat" + ''; //y error what will be the code to replace background-image of div 
    </script> 
</body> 

</html> 
+0

嘗試'style.backgroundImage =' – NewToJS

回答

1

如果你想改變你的body的backgorund圖像,你可以做到這一點

與標籤 body元件

document.getElementsByTagName("body")返回集合(如陣列):

document.body.style.backgroundImage = "url(1.jpg)"; 
document.body.style.backgroundRepeat = "no-repeat"; 
//OR 
document.body.style.background = "url(1.jpg) no-repeat"; 

更新。由於我們只有一個機構,我們將使用document.getElementsByTagName("body")[0]

docs.

+0

謝謝,但爲什麼我們不能採取document.getElementByTagname(「body」); –

+1

@ sandeep_1994。您可以。 'document.getElementByTagname(「body」)'返回一組元素,所以你需要'document.getElementByTagname(「body」)[0]'。不過,我覺得這是做到這一點的正確方法。 – Zee

+0

什麼類型的元素集合請告訴我,如果我將索引更改爲[1] –

0

你的主要問題是可能(儘管你可能要實際的錯誤信息添加到您的問題),其getElementsByTagName()返回DOM元素的數組,而不是單一的一個。所以如果你改成

var y = document.getElementsByTagName("body")[0]; //array will contain a single element 
y.style.background = 'url(1.jpg) no-repeat'; //No need for your funky empty string concatenation 

我覺得你應該很好。

+0

如果我不使用[0]索引,那麼它也工作,那麼爲什麼你用它 –

+0

對不起,我不知道我理解。如果沒有'[0]'我的解決方案將無法工作,並且不是缺乏'[0]'什麼是破壞你自己的代碼? –

+0

好的感謝討論 –