在jQuery中动画/应用Transition addClass和removeClass?

y0u0uwnf  于 2023-06-05  发布在  jQuery
关注(0)|答案(5)|浏览(185)

我是jQuery和JavaScript的新手,通过在下一张幻灯片上添加和删除类“active”来制作一个简单的滑块,它工作正常,但看起来很丑,因为没有动画。有没有什么方法可以使添加和删除类的过程动画化?比如:

$('#next').on('click', function(){
    $('div.active').removeClass('active', duration: 500ms).next().addClass('active', duration: 500ms);})

Jquery documentation website中,我看到有一个animate函数,用于动画事物。在我的情况下可以使用这个功能吗?
更新:我还尝试在div和div.active上应用CSS过渡,但不起作用。
CSS:

.slider div {
        display: none;
        opacity: 0;
        -webkit-transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -ms-transition: opacity 1s ease-in-out;
        -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
    }

    div.active {
        display: inline-block;
        opacity: 1;
        -webkit-transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -ms-transition: opacity 1s ease-in-out;
        -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
    }
9gm1akwq

9gm1akwq1#

从不同用户的评论中,我知道css转换不能应用于display: none元素。因此,我应用了height 0px; opacity: 0;而不是display none,这对我来说很好。

.slider img{
 height: 0px;
 opacity: 0;
 display: block;
 -webkit-transition: opacity 2s ease;
 -moz-transition: opacity 2s ease;
 -ms-transition: opacity 2s ease;
 -o-transition: opacity 2s ease;
 transition: opacity 2s ease;
}

.slider img.active{
 height: 360px;
 opacity: 1;
 -webkit-transition: opacity 2s ease;
 -moz-transition: opacity 2s ease;
 -ms-transition: opacity 2s ease;
 -o-transition: opacity 2s ease;
 transition: opacity 2s ease;
}

感谢this fiddle的创建者给了我这个想法。

vddsk6oq

vddsk6oq2#

.active {
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}
hmtdttj4

hmtdttj43#

你不能真正的动画addClass或removeClass,但你可以添加一个过渡
你可以使用CSS:

.item {   
   opacity: 0
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -ms-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

.item.active{
   opacity: 1
}
dba5bblo

dba5bblo5#

添加动画类:

$(".otp-wrapper").addClass('test');

删除动画类:

$(".otp-wrapper").removeClass('test');

样式表:

.test {
        animation: shake 0.5s;
        animation-iteration-count: infinite;
      }

@keyframes shake {
        0% {
          transform: translateX(0);
        }
        25% {
          transform: translateX(5px);
        }
        50% {
          transform: translateX(-5px);
        }
        75% {
          transform: translateX(5px);
        }
        100% {
          transform: translateX(0);
        }
      }
      .err-msg{
        font-size:16px;
        font-weight:400;color: red;
      }

参考:https://www.w3schools.com/howto/howto_css_shake_image.asp

相关问题