简体   繁体   中英

Change the css style of multiple div on click?

I have ex 3 boxes, the red one should have at start a bigger size then the others (through css). Now, when I click on the green or yellow box the red gets smaller size same as green or yellow had before clicking. And the clicked one gets the CSS Style (size) of the red one. I want to make it with JQuery but don't know how?

 .r1, .r2, .r3{ width: 80px; height: 80px; margin: 40px; float: left; } .r1{ background-color: red; position: inherit; transform: scaleY(1.2); transform: scale(1.2); transform-origin: center; border: 2px solid #15dc6e; } .r2{ background-color: green; } .r3{ background-color: yellow; } 
 <div class="content"> <div class="r1"></div> <div class="r2"></div> <div class="r3"></div> </div> 
Fiddle: https://jsfiddle.net/cwx3ukra/16/

Try this out:

Codepen: https://codepen.io/samandalso/pen/qKrLLM

$(function() {
    $('.content div').on('click', function(){
      $('.content div').not($(this)).removeClass('scaled');
      $(this).toggleClass('scaled');
    });
});

 $(document).ready( () => { $('.content div').click( e => { // Remove zoom class from all elements $('.content div').removeClass('big'); // Only apply to the clicked element $(e.target).addClass('big'); }); }) 
 .r1, .r2, .r3 { width: 80px; height: 80px; margin: 40px; float: left; transform: scale(1); transition: all 500ms ease-out; } .r1 { background-color: red; } .r2 { background-color: green; } .r3 { background-color: yellow; } .big { transform: scale(1.2); border: 2px solid #15dc6e; transform-origin: center; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"> <div class="r1 big"></div> <div class="r2"></div> <div class="r3"></div> </div> 

Working JSFiddle Here

You can achieve a smooth transition using pure CSS:

.r1,
.r2,
.r3 {
  width: 80px;
  height: 80px;
  margin: 40px;
  float: left;
  transform: scale(1);
  transition: all 500ms ease-out;
}

.big {
  transform: scale(1.2);
  border: 2px solid #15dc6e;
  transform-origin: center;
}

The transition property will automatically transition from one rule to another. In this example, it transitions from transform: scale(1) to transform: scale(1.2) .

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