带显示的CSS不透明度转换:无 [英] CSS Opacity transition with display: none

查看:52
本文介绍了带显示的CSS不透明度转换:无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个菜单,想用javascript淡入.我希望它从 display:none opacity:0 过渡到 display:flex opacity:1 .但是,当我使用javascript将不透明度设置为1时,它不会过渡,而是突然捕捉为1,而如果我未将display设置为none,它就会平稳过渡.我想使用 display:none ,因为在菜单出现之前,我需要能够捕获鼠标在后台画布上的移动.我制作了一个代码笔来在此处进行演示.

I have a menu that I would like to fade in with javascript. I want it to transition from display: none and opacity: 0 to display: flex and opacity: 1. But when I set opacity to 1 using javascript, it doesn't transition, and instead abruptly snaps to 1, whereas If I do not set display to none, it gracefully transitions. I want to use display: none because before the menu appears I need to be able to catch mouse movement on a canvas in the background. I have made a codepen to demonstrate this here.

注意:我也希望能够使用Javascript淡出

我也查看了这个问题,但第一个建议的答案无法消失.

I have also taken a look at this question, but the first suggested answer isn't able to fade out.

谢谢!

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>

推荐答案

对于要淡入的元素,请勿使用 display:none . display:none 不会从您的显示中删除该元素.当它重新出现时,不会应用您的CSS动画.

Do not use display: none for elements you want to fade-in. display: none will remove the element from your display. It won't have your css animation applied when it reappears.

因此,您必须将JavaScript用于动画.将动画/显示逻辑保留在CSS中.

Consequently you would have to use JavaScript for the animation. Keep your animation/display logic in your CSS.

有一个古老的CSS技巧,您可以在屏幕上隐藏绝对 fixed 元素.使用left属性.

There is an old CSS trick where you hide absolute or fixed elements offscreen. using the left property.

const text = document.getElementById("text");
window.setTimeout( function() {
  text.classList.remove('hidden');
}, 1000);

window.setTimeout( function() {
  text.classList.add('hidden');
}, 5000)

#text {
  width: 500px;
  height: 100px;
  display: flex;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 3rem;
  color: white;
  align-items: center;
  justify-content: center;
  background-color: black;
  border-radius: 5px;
  opacity: 1;
  transition: opacity 500ms;
}
#text.hidden {
  left: -500000px;
  opacity: 0;
  transition: opacity 500ms, left 0ms 500s;
}

<div id="text" class='hidden'>Testing Testing 123</div>

>

这篇关于带显示的CSS不透明度转换:无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆