首页 > 解决方案 > 寻找一种有效的方法来动画切换类

问题描述

我有一个 CSS 类,left-margin: 150px我只想以动画方式运行它。jQuery 中的 ToggleClass 可以工作,但没有任何动画。 $(this).toggleClass("active", 1000, "easeInOutQuad");

我设法使用 addClass 和 removeClass 对其进行动画处理。但我想知道是否有更简单的方法可以做到这一点。它需要 10 行代码,而应该有更高效的东西。

有任何想法吗?

$(".box").on('click tap', function() {
if($(this).hasClass('active')){
      $(this).animate({
        marginLeft: "-=150px",
      }, 500, function() {
        $(this).removeClass('active');
      });    
}else{
      $(this).animate({
        marginLeft: "+=150px",
      }, 500, function() {
        $(this).addClass('active');
      });    
}
});


// $(this).toggleClass("active", 1000, "easeInOutQuad");
.box{
width: 100px;
height: 100px;
background-color: red;
}

.active{
margin-left: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"> BOX </div>

标签: javascripthtmljquerycss

解决方案


我会使用CSStransition来做到这一点。添加transition: margin-left 0.5s;(或类似)到您的.box样式规则:

$(".box").on('click tap', function() {
    $(this).toggleClass('active');
});
.box {
    width: 100px;
    height: 100px;
    background-color: red;
    transition: margin-left 0.5s; /* <== */
}

.active {
    margin-left: 150px;
}
<div class="box"> BOX </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读