简体   繁体   中英

how to toggle between styles using Javascript or jquery

I have a div with class of .ban2 and id of #banner2 .

I want to change the border-radius property of this div whenever I click on the div itself. Like when iI click it for the first time the border-radius becomes 0 and when I click again it goes back to 50% 0 0 50% .

I want to toggle between these 2 styles. in my .ban2Toggle class I have all the styles included, but the border radius is 0.

it is only working once like when I click it for the first time the border radius becomes 0. The next time I click it I don't know how to get it back to normal.

.banner .ban2{
  position: absolute;
  right: 0;
  top: 0;
  width: 40%;
  height: 63vh;
  background: #5a0980;
  border-radius: 50% 0 0 50%;
  transform: scaleY(1.6);
  display: flex;
  justify-content: center;
  align-items: center;
  transition: 1s ease;
}

$('#banner2').on('click', function(){
  $('#banner2').removeClass('ban2');
  $('#banner2').addClass('ban2Toggle');
});

For jQuery , you must use

$(element).toggleClass('className');

It will automatically add and remove it for you.

For JavaScript , you must use

element.classList.toggle('className'); 

It will automatically add and remove it for you.

Example Snippet (Run)

 $('#banner2').on('click', function() { $('#banner2').toggleClass('ban2Toggle'); });
 .banner .ban2 { position: absolute; right: 0; top: 0; width: 40%; height: 63vh; background: #5a0980; border-radius: 50% 0 0 50%; transform: scaleY(1.6); display: flex; justify-content: center; align-items: center; transition: 1s ease; } .banner .ban2.ban2Toggle { border-radius: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="banner"> <div id="banner2" class="ban2">Lorem Ipsum</div> </div>

Following the answer from BOZ you need to do it like this:

html:

<div id="banner2" class="ban2"></div>

script:

$('#banner2').on('click', function(){
  $('#banner2').toggleClass('ban2');
  $('#banner2').toggleClass('ban2Toggle');
});

take a variable of naming flag=false; When you click on the button change the state of the flag variable to true When the flag is true make border radius 0 using conditional rendering When click again make flag false again When the flag is false make border radius 50 using again conditional rendering

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