简体   繁体   English

如何使用 Javascript 或 jquery 在样式之间切换

[英]how to toggle between styles using Javascript or jquery

I have a div with class of .ban2 and id of #banner2 .我有一个.ban2类和#banner2 .ban2 id 的 div。

I want to change the border-radius property of this div whenever I click on the div itself.每当我单击 div 本身时,我都想更改此 div 的 border-radius 属性。 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% .就像我第一次点击它时,border-radius 变为 0,当我再次点击时,它又回到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.在我的.ban2Toggle类中,我包含了所有样式,但边框半径为 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.它只工作一次,就像我第一次单击它时边框半径变为 0。下次我单击它时,我不知道如何让它恢复正常。

.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对于jQuery ,您必须使用

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

It will automatically add and remove it for you.它会自动为您添加和删除它。

For JavaScript , you must use对于JavaScript ,您必须使用

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:按照BOZ 的回答,您需要这样做:

html: 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;取一个命名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当您单击按钮时,将标志变量的状态更改为 true 当标志为 true 时使用条件渲染使边框半径为 0 再次单击时再次使标志为 false 当标志为 false 时再次使用条件渲染使边框半径为 50

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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