1. 程式人生 > 其它 >CSS實現 文字逐行顯示&文字逐個顯示

CSS實現 文字逐行顯示&文字逐個顯示

一,文字逐行顯示

HTML:

<div className="LetterToFuture__homeTexts">
     {Array.from(new Array(5)).map((_, idx) => (
       /* eslint-disable-next-line react/no-array-index-key */
          <div key={idx} className="LetterToFuture__homeText" />
      ))}
 </div>

CSS:由於字型效果比較特殊,所以每行文字採用的是圖片

$fadeInDur: 1500ms;
$textWidth: "231px", "124px", "97px", "96px", "213px";

.LetterToFuture__homeTexts 
{ display: flex; flex-direction: column; align-items: center; justify-content: flex-start; } .LetterToFuture__homeText { background: url(../../images/text_1.png) no-repeat center center / 100% 100%; height: 15px; margin-top: 25px; animation: slide-up-in #{$fadeInDur} ease-out both 1/*infinite
*/; &:nth-child(1) { margin-top: 15px; } /* 官網的 list.nth 寫法 not working - https://stackoverflow.com/questions/53155503/how-to-find-the-scss-index-of-the-element-in-the-list */ /*@debug list.nth([line1, line2, line3], -1);*/ /*@debug list.nth(10px 12px 16px, 2);*/ /*@debug "------------------------------------------------------------------------------------------";
*/ /* 正常 */ /*@debug nth($textWidth, 1);*/ @for $idx from 1 through 5 { &:nth-child(#{$idx}) { animation-delay: #{($idx - 1) * $fadeInDur}; background-image: url(../../images/text_#{$idx}.png); width: #{nth($textWidth, $idx)}; } } } @keyframes slide-up-in { 0% { opacity: 0; transform: translate(0, 15px); } 100% { opacity: 1; transform: translate(0, 0); } }

 

以上實現效果是:每行文字位移由下至上,透明度從0到1,逐漸顯示,如果你不想要位移變化,將css裡位移相關程式碼去掉即可。

 

二,文字逐個顯示

HTML:

<div className="WorldBookDayQuestionOne__textWrap">
    {text.split('').map((t, idx) => (
         /* eslint-disable-next-line react/no-array-index-key */
      <span key={idx} className="WorldBookDayQuestionOne__text">
                {t}
       </span>
     ))}
</div>

CSS:

$fadeInDur: 1500ms;

.WorldBookDayQuestionOne{
 
  &__textWrap {
    width: 150px;
    margin: 0 auto;
    margin-top: 100px;
    background-color: burlywood;
  }
  &__text {
    opacity: 0;
    animation: fade-in #{$fadeInDur} ease-out both  1/*infinite*/;
    @for $idx from 1 through 50 {
      &:nth-child(#{$idx}) {
        animation-delay: #{($idx - 1) * $fadeInDur};
      }
    }
  }
}

@keyframes fade-in {
  0% {
    opacity: 0;
  }

  100%  {
    opacity: 1;
  }
}

以上實現效果是:文字透明度由0到1逐個顯示,當一行顯示不下的時候會自動往下一行摺疊,一行顯示多少文字取決於父元素容器大小。