简体   繁体   中英

jquery click different div and change color and reset the other div color

I try that when change color in div with click over there, and the other links reset his color to original if until click over this other divs

I have test for see this, here

 .content { position: relative; width: 400px; height: 35px; line-height: 35px; margin-top: 7px; margin-bottom: 7px; border: 1px solid; cursor: pointer; cursor: hand; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content n1" style="background-color:pink;" onclick="$(this).css('background-color','green');">Number 1</div> <div class="content n1" style="background-color:blue;" onclick="$(this).css('background-color','green');">Number 2</div> <div class="content n1" style="background-color:orange;" onclick="$(this).css('background-color','green');">Number 3</div> <div class="content n1" style="background-color:brown;" onclick="$(this).css('background-color','green');">Number 4</div> 

If you can see the test link, when i do click change each div to color green, the idea it´s in each click only change color of div i do click, and reset color to original background color the other divs

I don´t know i can do this, if you can help me perfect, thank´s, regards

One option is adding a class with green background(In this example the class is .greenClass ). When clicked, remove the class .greenClass on all .content and only add the class on the clicked element.

 $(".content").click(function() { $(".content").removeClass('greenClass'); $(this).addClass('greenClass'); }); 
 .content { position: relative; width: 400px; height: 35px; line-height: 35px; margin-top: 7px; margin-bottom: 7px; border: 1px solid; cursor: pointer; cursor: hand; } .greenClass { background-color: green!IMPORTANT; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content n1" style="background-color:pink;">Number 1</div> <div class="content n1" style="background-color:blue;">Number 2</div> <div class="content n1" style="background-color:orange;">Number 3</div> <div class="content n1" style="background-color:brown;">Number 4</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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