首页 > 解决方案 > 如何更好地回写而不是 .css()?

问题描述

$(".box1").click(function() {
  $(this).animate({
      left: "300"
    }, 1000)
    .fadeOut(1000, function() {
      $(this).css("left", "0px").show()
    })
})
body {
  display: flex;
  justify-content: center;
  margin-top: 300px;
}

.box1 {
  width: 100px;
  height: 100px;
  background-color: rgb(255, 123, 123);
  position: relative;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<div class="box1"><a>box1</a></div>

这是框移动和回退代码。

但是 reback 使用 .css() 写起来不容易让人看懂。

如何更好地回写而不是 .css() ?

标签: javascripthtmljquerycss

解决方案


由于所有动画样式都是通过内联样式完成的,您可以style从 CSS 类中删除该属性以重置原始样式。

$(".box1").click(function() {
  $(this).animate({
      left: "300"
    }, 1000)
    .fadeOut(1000, function() {
      $(this).removeAttr("style");
    })
})
body {
  display: flex;
  justify-content: center;
}

.box1 {
  width: 100px;
  height: 100px;
  background-color: rgb(255, 123, 123);
  position: relative;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<div class="box1"><a>box1</a></div>


推荐阅读