2011-09-21 106 views
0

我必須使用JavaScript更改div的背景。我已經設法做到這一點, 使用document.getElementById('test').style.background = "url('img/test.jpg')";使用javascript更改背景

現在,我該如何改變其他屬性,如重複,滾動等?

我要用於測試的CSS是像

background: #f00 url('img/test.jpg') no-repeat fixed 10px 10px; 

我不能使用jQuery,因爲我不希望包括庫只是一個小事情。

回答

1

使用這些屬性創建一個類,然後通過javascript分配/刪除該類。

4

而不是用javascript設置所有的CSS屬性。我會建議爲這個元素創建一個額外的CSS規則與某些類。然後在你需要的時候使用javascript從這個元素添加或刪除這個類。

例如,

function changeBG(){ 
    var element = document.getElementById('test'); 
    element.setAttribute("class", 'newBG'); //For Most Browsers 
    element.setAttribute("className", 'newBG'); //For IE; harmless to other browsers. 
} 
-1

這會給類的DOM元素

document.getElementById('test').className = 'cssName' 
2

下面應該工作:

document.getElementById('test').style.background = "#f00 url('img/test.jpg') no-repeat fixed 10px 10px" 

或者您可以使用個別屬性,例如樣式對象的backgroundColor。有關樣式對象的各種屬性,請參見here

0

大家都建議我也更喜歡使用class,但如果你堅持,你使用CSS

document.getElementById('test').style.background = "url('img/test.jpg') no-repeat fixed你可以使用JS這個「

0

使用一個樣式屬性變化的背景:

document.getElementById('test').style.background 
document.getElementById('test').style.backgroundAttachment 
document.getElementById('test').style.backgroundClip 
document.getElementById('test').style.backgroundColor 
document.getElementById('test').style.backgroundImage 
document.getElementById('test').style.backgroundOrigin 
document.getElementById('test').style.backgroundPosition 
document.getElementById('test').style.backgroundPositionX 
document.getElementById('test').style.backgroundPositionY 
document.getElementById('test').style.backgroundRepeat 
document.getElementById('test').style.backgroundSize 

http://msdn.microsoft.com/en-us/library/ms535240%28v=vs.85%29.aspx