最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to use css within a javascript function - Stack Overflow

programmeradmin0浏览0评论

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. But I am not getting the way to call CSS using Javascript. Please help me out.

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. But I am not getting the way to call CSS using Javascript. Please help me out.

Share Improve this question edited Nov 23, 2011 at 0:48 Jonathan Leffler 755k145 gold badges949 silver badges1.3k bronze badges asked Apr 9, 2009 at 9:09 RammohanRammohan
Add a ment  | 

5 Answers 5

Reset to default 4

In jQuery, you may use the css method to change the background-color of the cell:

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

And in plain 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).

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.

e.g I want to change to this border+background style, so I'll define a class in my 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.

It also, quite importantly adds semantic value. Self documenting code is a very good thing.

To set one css property:

$("#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";
发布评论

评论列表(0)

  1. 暂无评论