javascript - CSS:淡出完成时如何隐藏?

标签 javascript html css

我正在使用此处的 snackbar 代码 https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_snackbar ,它有一个超时功能,可以在淡出完成时隐藏 div。它工作正常,但不高度同步。有时我会看到淡出突然停止,而在其他情况下,它会在淡出后重新出现,然后很快消失。

将淡出与隐藏同步而不是依赖于硬编码超时会很好,但经过几次尝试后我不知道如何实现这一点。请注意,由于一些技术限制,我无法使用高级 css 或 html 功能,也无法使用 jquery。

<html>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=11'>
<style type='text/css'>
#snackbar {
  visibility: hidden;
  min-width: 250px;
  margin: auto;
  background-color: #c8bed9;
  color: #000000;
  text-align: center;
  transform: translateX(-50%);
  border-radius: 2px;
  padding: 16px;
  position: fixed;
  z-index: 1;
  left: 50%;
  bottom: 30px;
  font-weight: bold;
  font-family: "Arial", Times, serif;
  font-size: 20px;
}

#snackbar.show {
  visibility: visible;
  animation: fadein 0.5s, fadeout 0.5s 2.5s;
}

@keyframes fadein {
  from {bottom: 0; opacity: 0;}
  to {bottom: 30px; opacity: 1;}
}

@keyframes fadeout {
  from {bottom: 30px; opacity: 1;}
  to {bottom: 0; opacity: 0;}
} 
</style>
</head>
<body>
<div id="snackbar">This should show some text and some message if needed...</div>
<script>
function terminate()
{
    var elm = document.getElementById("snackbar");
    setTimeout(function() {
        elm.className = "show";
        document.getElementById("loading_wheel").style.display = "none";
    }, 200);     
    setTimeout(function() {
        elm.className = "";
    }, 3000);
    return false;
}
window.onload = terminate;
</script>
</body>
</html>

最佳答案

不要使用 fromto,而是使用如下所示的百分比:

@keyframes fadein {
    0% {bottom: 0; opacity: 0; display: none;}
    1% {bottom: 0; opacity: 0; display: block;}
    100% {bottom: 30px; opacity: 1; display: block;}
}

@keyframes fadeout {
    0% {bottom: 30px; opacity: 1; display: block;}
    99% {bottom: 0; opacity: 0; display: block;}
    100% {bottom: 0; opacity: 0; display: none;}
} 

这将使您能够解决无法设置动画显示的问题,同时仍然能够淡入和淡出。您可能需要使用百分比,但通常,您只想在开始时或在结束时立即翻转显示。

关于javascript - CSS:淡出完成时如何隐藏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60460655/

相关文章:

html - 切换分辨率时布局会发生变化

php - 样式化 "order by desk"查询表

html - 禁用网页的 Internet Explorer 11 阅读 View

HTML/CSS - 如何让表单内的标签动画化?

php - Avada 主题 - 子菜单定制 2

javascript - 如何在 Chrome 和 Firefox 中将此字符串转换为 Javascript 日期?

javascript - 在 setTimeout 中设置 CSS 不更新

javascript - 如何在 React 中从数组状态中删除元素?

javascript - 修改Superfish菜单jQuery插件

html - 带有 ClickEvent 的下拉菜单