javascript - 显示 : none 的 CSS 不透明度过渡

标签 javascript css css-transitions

这个问题在这里已经有了答案:





css transition doesn't work if element start hidden

(5 个回答)


上个月关门。




我有一个我想用 javascript 淡入的菜单。我希望它从 display: none 过渡和 opacity: 0display: flexopacity: 1 .但是当我使用 javascript 将 opacity 设置为 1 时,它不会转换,而是突然捕捉到 1,而如果我没有将 display 设置为 none,它会优雅地转换。我想使用 display: none因为在菜单出现之前,我需要能够在后台的 Canvas 上捕捉鼠标移动。我做了一个codepen来演示这个here .
注意:我也希望能够使用 Javascript 淡出
我也看过this question ,但第一个建议的答案无法淡出。
谢谢!

text = document.getElementById("text");
window.setTimeout((function () {
  text.style.display = "flex";
  text.style.opacity = "1";
}), 2000)
#text {
  display: none;
  opacity: 0;
  width: 500px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 3rem;
  color: white;
  align-items: center;
  justify-content: center;
  transition-duration: 2s;
  background-color: black;
  border-radius: 5px;
}
<div id="text">Testing Testing 123</div>

最佳答案

尽管看起来很奇怪,但答案是在代码中添加一行,如下所示:

window.setTimeout((function () {
  text.style.display = "flex";
  document.body.offsetHeight;  // Yes, this line!
  text.style.opacity = "1";
}), 2000);
除了它在您的页面中执行“读取”数据之外,这一行没有什么特别之处(任何从 DOM 读取数据的操作都可以工作)。这样做是强制浏览器布局(或重排)页面。这很重要,因为一般来说,如果您执行一系列“写入”操作 - 例如添加一个元素或设置它的样式,浏览器会将它们批处理并一次执行它们。这意味着当您将元素的不透明度设置为0,然后设置为1时,浏览器会将这些操作批处理并在页面重排之前将它们一起执行,因此没有动画。通过在两者之间插入写入操作,浏览器能够从元素的透明状态到完全不透明的状态进行动画处理。
让它消失有点不同:
text = document.getElementById("text");

window.setTimeout((function () {
  text.style.display = "flex"; // write operation
  document.body.offsetHeight; // read operation which forces reflow

  text.addEventListener('transitionend', function listener1() {
    text.removeEventListener('transitionend', listener1);
    
    text.addEventListener('transitionend', function listener2() {
      text.removeEventListener('transitionend', listener2);
      text.style.display = 'none'; // remove text
    });
    
    window.setTimeout(function () {
      text.style.opacity = 0.1; // hide text
    }, 1000);
  });
  
  text.style.opacity = 1; // write operation - show text
  
}), 2000);
最好在开始新的过渡之前等待上一个过渡完成。在事件触发后删除事件监听器也是一种很好的做法。在从 DOM 中删除元素之前,您必须等待转换完成。在设置触发动画的样式之前无需执行读取操作,因为页面已经布局,不透明度设置为 1。我将不透明度设置为 0.1,以便您可以看到元素实际上消失了。
你可以看到一个JFiddle here.

关于javascript - 显示 : none 的 CSS 不透明度过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64000697/

相关文章:

javascript - 用于动态页面加载的 Bootstrap 预输入选择器

水平滚动列表项的 CSS 转换问题

html - 如何在框架内缩放图像

javascript - promise Js : Wait till promise fulfilled

javascript - 如何替换active x控件表单javascript项目

html - 在 anchor 标签上按下任何键盘键时,轮廓偏移的变化是预期的行为吗?

android - 如果受主题颜色影响, ListView 的颜色

html - 当 css 过滤器应用于父转换时图像不显示

javascript - R Shiny 数据表: prevent deselection of an already selected row when you click on it again

javascript - 再次运行函数时,它不会读取全局数组