首页 > 解决方案 > javascript 函数是否与使用的引导程序版本密切相关?

问题描述

我创建了一个函数来分割段落中的每个字母以创建打字效果。但是,休息几天后,我发现效果相反,即字母消失了。长话短说,为了达到所谓的写作效果,我试着逐字逐句地对想要的段落进行动画处理。整个过程是成功的,但是在我不得不更改引导程序版本之后,该函数的行为是对立的。启动网页时,段落逐渐消失。问题的原因可能是什么?代码附在下面。提前致谢!

   <pre>
    index.html
    </pre> 
        

      <div class="id">

              <h1 class="title">

                  Hot Beans Coffee Shop
              </h1> 

            <p class="subtitle">

                "Born out of unique appreciation for coffee"
                
            </p>

            <script src="./app.js"></script>
            
            
        </div>
    
    
  <pre>
       app.js
    </pre>
    
    
       const text= document.querySelector(".id.subtitle");

       const strText=text.textContent;

       const splitText= strText.split("");

       text.textContent = "";
    
       for ( let i=0 ; i<splitText.length; i++){

           text.innerHTML+="<span>" + splitText[i] + "</span>";
      }
    
        let char=0;

        let timer=setInterval(onTick, 50);
    
       function onTick(){

           const span=text.querySelectorAll("span")[char];

           span.classList.add("fade");

           char++;

            if(char === splitText.length){

            complete();

            return; 
           }
        }
    
        function complete(){

            clearInterval(timer);

             timer=null;
      }
    
    
   <pre>
       app.js
    </pre>
        
   

         
            span{

                opacity: 0;
 
                transition: all 0.3 s ease;
    
    
    
            } 

          span.fade{
        
             opacity: 1;
        
    
           }

标签: javascripthtmlcssbootstrap-5

解决方案


似乎它通过几个更改工作正常。将选择器从".id.subtitle"更改为 " .id .subtitle"并将不透明度从1更改为0

const text = document.querySelector(".id .subtitle");
const strText = text.textContent;
const splitText = strText.split("");
text.textContent = "";

for (let i = 0; i < splitText.length; i++) {
  text.innerHTML += "<span class='typing-text'>" + splitText[i] + "</span>";
}

let char = 0;
let timer = setInterval(onTick, 50);
function onTick() {
  const span = text.querySelectorAll(".typing-text")[char];
  span.classList.add("custom-fade");
  char++;
  if (char === splitText.length) {
    complete();
    return;
  }
}

function complete() {
  clearInterval(timer);
  timer = null;
}
span.typing-text{
    opacity: 0;
    transition: all 0.3 s ease;
} 

span.typing-text.custom-fade{
    opacity: 1;
}
 <div class="id">
      <h1 class="title">Hot Beans Coffee Shop</h1> 
      <p class="subtitle">"Born out of unique appreciation for coffee"</p>
 </div>
    
    

        
   

         


推荐阅读