如何在jquery中添加2个带延迟的类

时间:2017-03-31 08:56:13

标签: jquery

我尝试使用jquery创建动画。 当我单击黄色框时,它将移动到中心容器(.radius),之后该框将更改为容器宽度(删除.radius添加.full)。 用jquery在单个事件中添加2个类是否可行? 或者还有其他方法吗? 谢谢

$(document).ready(function(){
  var go = $('.expand');

  function erase(){
    $(go).removeClass('radius');
    //$(go).addClass('full');
  }
  $(go).on('click', function(){
    $(this).addClass('radius').delay(500, erase);
  });

});
.boxContainer {
  position: relative;
  overflow: hidden;
  width: 1170px;
  height: 800px;
  border: 3px solid #cecece;
  margin: 0 auto;
  padding: 0 15px;
}

.expand {
  position: absolute;
  top: 5px;
  left: 5px;
  width: 50px;
  height: 50px;
  background-color: yellow;
  cursor: pointer;
  transition: 300ms all ease-in-out;
}

.radius {
  top: 50%;
  left: 50%;
}

.full{
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxContainer">
  <div class="expand">
  </div>
</div>

1 个答案:

答案 0 :(得分:3)

要实现您的需求,您可以使用setTimeout()来延迟修改500ms的课程。试试这个:

var $go = $('.expand');

$go.on('click', function() {
  $(this).addClass('radius')
  setTimeout(function() {
    $go.removeClass('radius').addClass('full');
  }, 500);
});

话虽这么说,一个更好的解决方案是使用关键帧在CSS中完成所有这些:

&#13;
&#13;
$('.expand').on('click', function() {
  $(this).addClass('animate')
});
&#13;
.boxContainer {
  position: relative;
  overflow: hidden;
  width: 1170px;
  height: 800px;
  border: 3px solid #cecece;
  margin: 0 auto;
  padding: 0 15px;
}

.expand {
  position: absolute;
  top: 5px;
  left: 5px;
  width: 50px;
  height: 50px;
  background-color: yellow;
  cursor: pointer;
  transition: 300ms all ease-in-out;
}

@keyframes expand {
  50% {
    width: 50px;
    height: 50px;
    top: 50%;
    left: 50%;
  }
  100% {
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
}

.animate {
  animation: expand 1s forwards;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxContainer">
  <div class="expand"></div>
</div>
&#13;
&#13;
&#13;