首页 > 解决方案 > 显示父级时 CSS 翻译动画不起作用

问题描述

有类似的问题thisthis,但不要解决这种情况。

目标是在显示其父级时使用 CSS 翻译将菜单滑到屏幕上。但是,显示父级然后应用 CSS 类来触发翻译会立即发生,而不是随着时间的推移发生。实际上,没有动画。

JavaScript 可用于将子元素滑动到屏幕上,但目标是在 CSS 中保留尽可能多的动画逻辑。

将不透明度设置为 0 不起作用,因为我们需要菜单及其父级不占用任何空间或成为布局的一部分。

代码笔: https ://codepen.io/Crashalot/pen/YzXmjYj

function toggleSidebar() {
  $("#sidebar").toggleClass("show");
}


$("#button").on("click", function() {
    toggleSidebar();
});
body {
  margin: 0;
  padding: 0;
}

#button {
  position: fixed;
  top: 0;
  left: 200px;
  width: 150px;
  height: 50px;
  background: yellow;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 8;
  cursor: pointer;
}

#sidebar {
  display: none;
}

#sidebar.show {
  display: block;
}

.overlay {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background: red;
  z-index: -1;
}

.menuBox {
  width: 200px;
  height: 100vh;
  background: blue;
	transition: 0.3s ease-in-out;				       
  transform: translate(-100%);
}

#sidebar.show .menuBox {
  transform: translate(0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sidebar">
  <div class="overlay"></div>
  <div class="menuBox"></div>
</div>


<div id="button">CLICK ME</div>

标签: javascriptjqueryhtmlcss

解决方案


你不能动画显示:无;将不透明度设置为 0,然后在切换类上设置为 1。这是适合您的 CodePen。;)

我为切换事件添加了一个按钮。如果您需要更多帮助,请告诉我!

在此处输入链接描述

$(".btn").on("click", toggleSidebar);

function toggleSidebar() {
  $("#sidebar").toggleClass("show");
}
body {
  margin: 0;
  padding: 0;
}

#sidebar {
  opacity: 0;
  transition: all 300ms ease-in-out;
}

#sidebar.show {
  display: block;
  opacity: 1;

}

.overlay {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background: red;
  z-index: -1;
}

.menuBox {
  width: 200px;
  height: 100vh;
  background: blue;
	transition: 300ms ease-in-out;				       
  -webkit-transform: translate(-100%);
}

#sidebar.show .menuBox {
  -webkit-transform: translate(0);
}

.btn {
  position: absolute;
  top: 10px;
  left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sidebar">
  <div class="overlay"></div>
  <div class="menuBox"></div>
</div>

<button class="btn">Click</button>


推荐阅读