Javascript javascript函数中的css代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8561492/
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
Css code in javascript function
提问by petko_stankoski
I have this javascript method:
我有这个 javascript 方法:
<script type="text/javascript">
function MyFunction(sender, eventArgs) {
if (someCondition) {
//css
}
}
</script>
The css code I want to be executed is:
我要执行的css代码是:
<style type="text/css">
.classInsideTheClassWhichEntersTheIf
{
background: url(Images/myImage.png) !important;
}
</style>
but only for those cells that enter the if condition above. If I write it outside it works but for every cell. Is something like this possible? If yes, how to do it?
但仅限于那些进入上述 if 条件的单元格。如果我把它写在外面,它可以工作,但适用于每个单元格。这样的事情可能吗?如果是,怎么做?
回答by Ashwin Krishnamurthy
There are several ways to do this.
有几种方法可以做到这一点。
Option 1.
选项1。
<script type="text/javascript">
function MyFunction(sender, eventArgs) {
if (someCondition) {
someelement.style.cssText = "background: url(Images/myImage.png) !important;"
}
}
</script>
Option 2.
选项 2。
<script type="text/javascript">
function MyFunction(sender, eventArgs) {
if (someCondition) {
someelement.className = "someclass"
}
}
</script>
where,
在哪里,
<style>
.someclass{
background: url(Images/myImage.png) !important;
}
</style>
Option 3
选项 3
<script type="text/javascript">
function MyFunction(sender, eventArgs) {
if (someCondition) {
someelement.setAttribute('style', 'background: url(Images/myImage.png) !important;');
}
}
</script>
Here is a pseudo code,
这是一个伪代码,
if(condition)
someelement.style.cssText = "background: url(Images/myImage.png) !important;";
回答by Niet the Dark Absol
<script type="text/javascript">
function MyFunction(sender, eventArgs) {
if (someCondition) {
someelement.style.backgroundImage = "url(Images/myImage.png)";
}
}
</script>
!important
is unnecessary here, because inline styles override non-inline styles.
!important
在这里是不必要的,因为内联样式会覆盖非内联样式。
回答by KSDaemon
You can modify the style property of elements that you need. But more flexible method is to define a css-class with that css-code, and just add this class to filtered elements.
您可以修改所需元素的样式属性。但更灵活的方法是使用该 css-code 定义一个 css-class,并将此类添加到过滤元素中。
回答by Mohammad Saberi
Imagine that you have a cell with id="myCell"
and your condition is true for what you want.
Now you can do it using something like this:
想象一下,您有一个细胞,id="myCell"
并且您的条件符合您的要求。现在你可以使用这样的东西来做到这一点:
$(document).ready(functio() {
function SET(id) {
$('#'+id).css('background-image','yourNewImage.png');
}
if (condition == true) {
SET('myCell');
}
});
Using .css
, you can assign any value to each CSS property for each element. Here I changed the background-image.
使用.css
,您可以为每个元素的每个 CSS 属性分配任何值。在这里,我更改了背景图像。