开发者

change background using javascript

开发者 https://www.devze.com 2023-04-06 21:32 出处:网络
I have to change the background of a div using JavaScript. I have managed to do that, using document.getElementById(\'test\').style.background = \"url(\'img/test.jpg\')\";

I have to change the background of a div using JavaScript. I have managed to do that, using document.getElementById('test').style.background = "url('img/test.jpg')";

Now, how do i change other properties like repeat, scroll,etc?

The css i want for the test is like

background: #f00 url('img/test.jpg') no-repeat fixed 10px 1开发者_运维百科0px;

I cannot use jQuery, since I do not want to include the library for only a small thing.


Instead of setting all the css properties with javascript. I would suggest to create an additional css rule for this element with certain class. And then use javascript to add or remove this class from this element when you need it.

Eg.

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


Below should work:

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

Or you can use individual properties such as backgroundColor of style object. See here for various properties of style object.


Make a class with those properties, and then just assign/remove that class through javascript.


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

See following:
http://www.w3schools.com/jsref/prop_style_background.asp


As everyone suggests I also prefer using a class, but if you insist you can use JS for this as you use CSS

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


Use next style properties for changing background:

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


This will give the class to the dom element

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

精彩评论

暂无评论...
验证码 换一张
取 消