javascript - 寻找一种有效的方法来动画切换类
问题描述
我有一个 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>
解决方案
我会使用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>
推荐阅读
- vega-lite - Vega-lite 中的桑基图
- api-platform.com - Api平台demo项目安装问题
- javascript - ForEach 等待 Observable 订阅
- eclipse - 如何在 Eclipse 中离线插入 Groovy 编辑器和编译器?
- flutter - 从小部件列表中动态添加和删除元素
- git - 如何解决这个问题?ssh:连接到主机 github.com 端口 22:连接超时致命
- python - 将参数添加到类的python装饰器
- asp.net-core - 为 Autofac 模块提供 IOptions
- python - 有没有一种简单的方法可以从布尔表达式中从 pandas DataFrame 中提取行?
- azure - 数百个 Azure 函数实例来处理事件中心事件