2011-09-21 132 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