【问题标题】:Looking for an efficient way to animate toggle class寻找一种有效的方法来动画切换类
【发布时间】:2020-11-11 23:09:27
【问题描述】:

我有一个具有 left-margin: 150px 的 CSS 类,我只想以动画方式运行它。 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>

【问题讨论】:

标签: javascript html jquery css


【解决方案1】:

我会使用CSS transition 来做这件事。将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>

【讨论】:

    猜你喜欢
    • 2023-01-19
    • 2011-11-08
    • 2013-11-08
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多