简体   繁体   English

如何在JavaScript函数中使用CSS

[英]How to use css within a javascript function

I am using jQuery monthly calender, in which every day is a cell, onClick in the cell, I am able to print the alert, but I also want to change the background color of the cell, on which I clicked. 我正在使用jQuery每月日历,其中每天是一个单元格,在该单元格中的onClick上,我可以打印警报,但我还想更改单击的单元格的背景颜色。 But I am not getting the way to call CSS using Javascript. 但是我没有办法使用Javascript来调用CSS。 Please help me out. 请帮帮我。

In jQuery, you may use the css method to change the background-color of the cell: 在jQuery中,您可以使用css方法更改单元格的背景颜色:

// let's say this is in a loop
$(this).css('background-color', '#f00');

And in plain JavaScript: 在纯JavaScript中:

var element = document.getElementById("myElement");
element.style.backgroundColor = "#fff";

Steve 史蒂夫

Using JS to change the style property of any element creates a very high specificity rule which is hard to detect and remove, and less flexible when dealing with multiple style effects (say you wanted a border as well as a background, now you have twice as much work to do). 使用JS更改任何元素的style属性会创建一个非常高的特异性规则,该规则很难被检测和删除,并且在处理多种样式效果时灵活性较差(例如,您既需要边框又需要背景,现在您有了两倍的边框很多工作要做)。

Almost invariably it is far better from a maintenance, flexibility, and separation-of-concerns point of view not to modify the style of an element directly, but to change it's class and let CSS do the work for you. 从维护,灵活性和关注点分离的角度来看,几乎总是要好得多, 不要直接修改元素的样式,而要更改它的类并让CSS为您完成工作。

eg I want to change to this border+background style, so I'll define a class in my CSS 例如,我想更改为border + background样式,因此我将在CSS中定义一个类

.highlight
{
  border: 1px solid black;
  background: white;
}

and then I'll modify the element where I need to like so: 然后在需要的地方修改元素:

document.getElementById('myElementId').className += " highlight"; //note the space

Now in practice I'd actually wrap that class modifying code in a more general wrapper to protect myself from assigning the same class twice, and make removing it again easier, but in principle you can see that it would now be trivial to change the effect of "highlight" at just a single point, it allows for normal cascading, and it's much easier to detect the element has a highlight class than it is to check if it's got a background colour of FOO and a border of BAR. 现在在实践中,我实际上将类修改代码包装在一个更通用的包装器中,以保护自己免于两次分配相同的类,并使再次删除它更加容易,但是原则上您可以看到更改效果现在变得微不足道了只需在单个点上显示“高光”,它就可以进行正常的级联,并且比起检查元素的背景色是否为FOO和边框是否为BAR,要容易得多。

It also, quite importantly adds semantic value. 同样,非常重要的是还增加了语义价值。 Self documenting code is a very good thing. 自我记录代码是一件非常好的事情。

To set one css property: 设置一个CSS属性:

$("#myCalender").css("background-color","SomeColor");

To set an entire class: 设置整个课程:

$("#myCalender").addClass("DifferentBGColorClass");

To change the background color you could use: 要更改背景颜色,您可以使用:

document.getElementById("").style.backgroundColor = "#ffffff";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM