首页 > 解决方案 > 将关键帧动画文本与容器中心对齐

问题描述

这是一个简单的显示文本动画代码。

我需要使用不同的字体大小,这导致文本以不同的垂直位置结束(请运行代码片段以了解我的意思)。

问题是我想将动画文本完美地对齐到它的垂直中间,container并将它水平对齐到左侧,即使字体大小发生了变化。

如果我position: absolutetextClass文本中删除淡入淡出,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% }
}

标签: javascripthtmlcss

解决方案


我想我明白了:

@-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 但它已经被元素使用。


推荐阅读