Change DIV background color with .click(function()

2019-06-22 13:30发布

How can I change background color with jQuery .click(function(){

div normal with Green color, when clicked change to red background color

<div class="stileone">
   Div Content
</div>

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-22 13:55
$(".stileone").on("click", function() {
    $(this).css("background", "red");
})

DEMO

查看更多
Bombasti
3楼-- · 2019-06-22 14:01

I know there are plenty answers here, but i thought I would point out, there are many ways to accomplish this and many with slightly different purpose.

Basic CSS Psuedo Classes are meant to handle stuff like this however, they are not always cross-browser compatible. For Instance, I don't think the following works in IE >=8, but it works in Chrome and IE9.

div:active { background-color: red; }

Then of course basic click to css change. This of course will make the change perminant though, without any other commands.

$("div").on("click", function() {
    $(this).css("background-color", "red");
});
//  OR
$("div").on("click", function() {
    $(this).css({ backgroundColor: "red" });
});

As shown earlier in answer, there is click to toggle class. In this case you create a class with your background desired and then toggle that class on and off based on click actions.

$("div").on("click", function() {
    $(this).toggleClass('back-red');
});

If you need a jQuery way to immitate :active, then you can make use of mousedown/up instead of simple click. This will allow you to effectivly "cross-browser" immitate the ':active` feature of CSS.

$("#div5").on("mousedown", function() {
    $(this).toggleClass('back-red');
})
.on("mouseup", function(e) {
    $(this).toggleClass('back-red');
});

Finally, the last feature way I can think of right now is to use a method that is currently broken in the NEWEST jQuery (1.8+), however, in all other jQuery's (1.72-) it seems to work fine. It's called the "toggle" method, and is usually used to define aa element showing and hiding. However in older versions it has an alternate feature wherein you can define call backs and thus create your own animations.

$("div").toggle(function() {
    $(this).css("background-color", "red");
}, 
function() {
    $(this).css("background-color", "");
});

See examples here!

查看更多
叼着烟拽天下
4楼-- · 2019-06-22 14:01

Work with .on(). You bind an event on your <div.stileone> when the event 'click' occurs, then you reference to your <div.stileone> object within the function with $(this). And toggleClass adds/removes the class every time the Event is triggered.

jQuery:

$('.stileone').on('click',function(){
  $(this).css('backgroundColor','red');
  // OR: if you want to work with a class
  $(this).toggleClass('redClass');
});

css:

.redClass {
background-color: red;
}
查看更多
闹够了就滚
5楼-- · 2019-06-22 14:18

you need to find the onclick event to the div, then use

.css("background-color:#00000;);
查看更多
登录 后发表回答