使用javascript更改背景

时间:2011-09-21 09:13:49

标签: javascript

我必须使用JavaScript更改div的背景。我设法做到了, 使用document.getElementById('test').style.background = "url('img/test.jpg')";

现在,我如何更改其他属性,如重复,滚动等?

我想要测试的CSS就像

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

我不能使用jQuery,因为我不想只为一个小东西包含库。

7 个答案:

答案 0 :(得分: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 :(得分:2)

下面应该有效:

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

或者您可以使用样式对象的backgroundColor等单个属性。有关样式对象的各种属性,请参阅here

答案 2 :(得分:1)

创建一个包含这些属性的类,然后通过javascript分配/删除该类。

答案 3 :(得分:1)

function displayResult()
{
document.body.style.background="#f3f3f3 url('img_tree.png') no-repeat right top";
}

见以下内容:
http://www.w3schools.com/jsref/prop_style_background.asp

答案 4 :(得分:0)

正如大家所说,我也更喜欢使用class,但如果你坚持使用JS就可以使用JS

document.getElementById('test').style.background = "url('img/test.jpg') no-repeat fixed“;

答案 5 :(得分: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

答案 6 :(得分:-1)

这将使类具有dom元素

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