1. 程式人生 > >解決JS setTimeout 傳入參無效果問題

解決JS setTimeout 傳入參無效果問題


    自己寫了一個文字的水平滾動的效果.JS程式碼如下:

           var tag = 0; //若不設定為全域性變數,不會左移
        function wordflow(id,minflow,maxflow){
            
               var  OText = document.getElementById(id)||document.getElementsByClassName(id)[0];
//                 alert(typeof(OText));
               var  currentLeft = parseInt(window.getComputedStyle(OText,null).left)||parseInt(OText.style.left);
               console.log(currentLeft);
               //右移
               if(currentLeft<maxflow &&tag==0){
                  currentLeft++;
                  if (currentLeft==maxflow) {
                    tag = 1;
                  }
               }
               //左移
               if(currentLeft>minflow &&tag==1)
               {
                    currentLeft--;
                    if (currentLeft==minflow) {
                    tag =0;
                    }
               }
               OText.style.left = currentLeft + "px";
              // console.log(OText.style.left);
            var timer = setTimeout(wordflow(id,minflow,maxflow),30);


         };
                  window.onload=function(){
                            wordflow('words',200,500);
                            console.log("123");
                  };



    CSS部分:
          #words{
      position:absolute;
      left:200px;
      top:100px;
      font-family:'宋體';
        font-size:30px;
        color:red;
        overflow:hidden;
     }


   HTML部分:
    <body>
<div id = "words" > 今天的天氣雖然下雨,但心情還是不錯哦!</div>             
   </body>


   執行完成之後發現報錯如下圖所示



  經過查閱資料後,發現setTimeout需要傳入函式指標,所以將setTimeout此段程式碼更改如下:
  wordflow.bind(null,id,minflow,maxflow) 採用函式時間繫結的方式.執行之後發現文字能按預期的水平迴圈滾動.