javascript - 将关键帧动画文本与容器中心对齐
问题描述
这是一个简单的显示文本动画代码。
我需要使用不同的字体大小,这导致文本以不同的垂直位置结束(请运行代码片段以了解我的意思)。
问题是我想将动画文本完美地对齐到它的垂直中间,container
并将它水平对齐到左侧,即使字体大小发生了变化。
如果我position: absolute
从textClass
文本中删除淡入淡出,container
但我会丢失从下到上的翻译动画!
注意: 我知道使用视口单位的缺点,但我确实需要使用那些(vw 和 vh)或 % 单位,而且我不允许使用 px em 等...
let textId = document.getElementById("textId");
// Text with 1vw font size
setTimeout(function(){
//Our Text
let myText = 'First text here';
//Define the font size
textId.style.fontSize = "1vw";
//append text to the elemnt
textId.innerHTML = `${myText}`;
//animate the text
textId.classList.add("animeShow");
textId.classList.remove("animeHide");
}, 1000);
// Hide Text by adding `animeHide` class
setTimeout(function(){
textId.classList.remove("animeShow");
textId.classList.add("animeHide");
}, 4000);
// Text with 3vw font size
setTimeout(function(){
let myText = 'Second text here';
textId.style.fontSize = "3vw";
textId.innerHTML = `${myText}`;
textId.classList.add("animeShow");
textId.classList.remove("animeHide");
}, 5000);
.container {
position: absolute;
overflow: hidden;
left: 10vw;
top: 51vh;
height: 26vh;
width: 88vw;
display: flex;
justify-content: center;
align-items: center;
outline: 0.1vw dashed orange;
}
.textClass {
position: absolute;
font-family: 'Open Sans', sans-serif;
font-weight: bold;
color: rgb(128, 128, 128);
left: 0.5vw;
opacity: 0;
}
.animeShow {
animation: Show 0.3s ease-in-out;
animation-delay: 0.5s;
animation-fill-mode: forwards ;
}
.animeHide {
animation: Hide 0.3s ease-in-out;
animation-fill-mode: forwards ;
}
@-webkit-keyframes Show {
from { opacity: 0; top: 30vh }
to { opacity: 1; top: 0vh }
}
@-webkit-keyframes Hide {
from { opacity: 1; top: 0vh }
to { opacity: 0; top: 30vh }
}
<div class = "container">
<p id="textId" class="textClass"></p>
</div>
我用这个没有成功:
transition: 200ms transform;
transform: translateY(-50%);
也使用这个:
@-webkit-keyframes Show {
from { opacity: 0; top: 0% }
to { opacity: 1; top: 50% }
}
解决方案
我想我明白了:
@-webkit-keyframes Show {
from { opacity: 0; padding-top: 10%; }
to { opacity: 1; padding-top: 0%; }
}
@-webkit-keyframes Hide {
from { opacity: 1; padding-top: 0%; }
to { opacity: 0; padding-top: 10%; }
}
我尝试使用 margin-top 但它已经被元素使用。
推荐阅读
- algorithm - 为什么我们有多项式算法可以将 SAT 减少到 3 SAT,但没有将 3 SAT 减少到 2 SAT?
- python - 使用pickle存储OAuth1Session的Flask会话
- c++ - 最大连续和
- javascript - 一段时间后 JQuery/CSS 动画中断
- perl - 在 Perl 中从 base64 创建 PDF
- javascript - 修复 Node Js 中的 Facebook JSON 编码
- azure-active-directory - Azure 前门服务阻止 Azure AD SSO
- visual-studio-code - vscode/LSP:使用断点调试 vscode 扩展
- javascript - 倒计时并在发生时更改变量
- sql - 将多行连接成一行并按日期分组