javascript - 显示父级时 CSS 翻译动画不起作用
问题描述
目标是在显示其父级时使用 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>
解决方案
你不能动画显示:无;将不透明度设置为 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>
推荐阅读
- android - 分页库仅在房间数据库中存储第一次获取的值
- php - PhpStorm:运行 PHP 服务器不起作用:找不到驱动程序
- c++ - 如何在 clang++ 中干净地进行格式化字符串连接
- c++ - 从当前时间戳计算每日午夜时间
- reactjs - React 和 Nest.js google auth 返回 CORS 错误
- firebase - 没有为“CollectionReference”类型定义方法“document”。颤振/火力基地
- php - 如何在 PHP 中使用其编号将一行替换为另一行
- google-chrome - 有没有办法无头运行 Google Lighthouse 测试?
- python - 尝试在 tkinter 帧后面计数时在分配之前引用的局部变量“计数”
- android - 参数类型SearchBar不能赋值给flutter中的参数类型Widget