点击时显示Div CSS动画

时间:2019-11-01 09:32:42

标签: jquery css

我有一个按钮,它将打开带有CSS动画的“菜单”。 就像动画中的淡入淡出/滑动:

现在,我想在单击时实现此动画反向(淡入/滑出动画) 但我不知道该怎么实现

https://jsfiddle.net/tafgd5mu/1/

var isOpen = false;
$("#Widget").click(function() {
  // Close
  if (isOpen == true) {
    isOpen = false;
    $("#Widget").html('Open')
    // Open
  } else {
    isOpen = true;
    $('<div class="widget ">DIV</div>').insertAfter("#Widget");
    $("#Widget").html('Close')
  }
})
@keyframes widget-slide-in {
  from {
    opacity: 0;
    bottom: 40;
  }
  to {
    opacity: 1;
    bottom: 80;
  }
}

.widget {
  width: 450px;
  height: 80%;
  overflow: hidden;
  border-radius: 3px;
  display: flex;
  position: fixed;
  bottom: 80px;
  margin: 20px;
  top: initial;
  background-color: #eef0f4;
  flex-direction: column;
  animation: widget-slide-in 0.25s ease-in-out;
  box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.1);
  transition: opacity 0.25s ease-in-out, bottom 0.25s ease-in-out;
  left: unset !important;
  right: 0 !important;
}

.button {
  position: fixed;
  bottom: 0;
  margin: 20px;
  top: initial;
  color: white;
  font-size: 16px;
  font-weight: 300;
  overflow: hidden;
  padding: 12px 23px;
  border: none;
  outline: none;
  cursor: pointer;
  pointer-events: all;
  background-color: #7ebd0b;
  font-family: 'Nunito', 'Helvetica', sans-serif;
  border-radius: 25px;
  box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.1);
  will-change: auto;
  width: auto;
  white-space: nowrap;
  left: unset !important;
  right: 0 !important;
}

.button>svg {
  margin-bottom: -3px;
  margin-right: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="Widget" class="button">Open</button>

2 个答案:

答案 0 :(得分:0)

如果您查看CSS,就会发现动画具有关键帧:

@keyframes widget-slide-in {
  from {
    opacity: 0;
    bottom: 40; }
  to {
    opacity: 1;
    bottom: 80; } 
}

如果您进一步检查代码,还可以看到Widget类使用了此动画。如果您创建了一组新的关键帧,并切换了fromto参数中的值,那么如果我对问题的理解正确的话,将获得所需的动画。

例如,您可以将其命名为widget-slide-out,然后按照isOpen == true将此动画添加到元素onClick中。您的jQuery代码。

但是,正如上面的评论者所建议的,我只会添加div元素一次或至少添加一次,然后再次将其删除。

您还可以考虑使用jQuery具有的.slideToggle()功能,因为我认为这种情况下可以使用它。

https://api.jquery.com/slidetoggle/

答案 1 :(得分:0)

最简单的方法是使用Jquery slideToggle()

此方法如文档中所述为所选元素在slideUp()和slideDown()之间切换。

https://api.jquery.com/slidetoggle/

https://www.w3schools.com/jquery/eff_slidetoggle.asp