如何从 JavaScript 调用 CSS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23441864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call CSS from JavaScript
提问by user3598626
I want to have different background images for different conditions (JS,HTML,CSS). For E.g: if(n=1),then image 1 else if(n=2),then image 2 etc.
我想针对不同的条件(JS、HTML、CSS)使用不同的背景图像。例如:if(n=1),则图像 1 else if(n=2),则图像 2 等。
采纳答案by Riad
It should be pretty easy in jQuery.
在 jQuery 中应该很容易。
if(n == 1){
$('your_image_element').css('background-image','url(your_first_img_path)') ;
}else if(n ==2){
// second image...
}
回答by Jameem
Try creating a Css class..After that you can set it to your control from javascript..
尝试创建一个Css 类..之后你可以将它设置为你的 javascript 控件..
document.getElementById("MyControl").className = "MyClass";
In the css class MyClassyou can set the background image..You can create another css class with different background image and set it according to the conditions..
在css类MyClass中你可以设置背景图片..你可以创建另一个具有不同背景图片的css类并根据条件进行设置..
回答by oley
Once you have picked the object you are manipulating, you can set its css properties directly from the script. E.g for the background image change on the body element:
选择要操作的对象后,您可以直接从脚本设置其 css 属性。例如,对于 body 元素上的背景图像更改:
var object = document.body;
object.style.backgroundImage="url('new_image.jpg')";
回答by RobG
One way is to use script to dynamically change a CSS rule, e.g.
一种方法是使用脚本来动态更改 CSS 规则,例如
var image;
if ( /*some condition */ ) {
image = 'a.png';
} else {
image = 'b.png';
}
document.write('<style type="text/css">.someClass {background-image:url("' + image + '");}<\/style>');
Of course there are more sophisticated ways to modify the rule, the above is just a basic method.
当然还有更高级的修改规则的方法,以上只是基本的方法。