2017-07-19 65 views
0

Script這是爲什麼返回revealPoint是不確定的,當它被定義

    var pointsArray = document.getElementsByClassName('point'); 

       var animatePoints = function(points) { 

        var revealPoint = function(index) { 

         points[index].style.opacity = 1; 
         points[index].style.transform = "scaleX(1) translateY(0)"; 
         points[index].style.msTransform = "scaleX(1) translateY(0)"; 
         points[index].style.WebkitTransform = "scaleX(1) translateY(0)"; 
        } 
       } 

       for (i = 0; i < pointsArray.length; i++) 

       { 
        revealPoint(i); 
       } 

       window.onload = function() { 
       var sellingPoints = document.getElementsByClassName("selling-points")[0]; 
        var scrollDistance = sellingPoints.getBoundingClientRect().top - window.innerHeight + 200; 

        window.addEventListener("scroll", function(event) { 
        if (document.documentElement.scrollTop || document.body.scrollTop >= scrollDistance) 
        { 
         animatePoints(pointsArray); 
        } 

        }); 
} 

該控制檯顯示,revealPoint是不確定的,它被定義的時候。

+1

你應該瞭解[在Javascript範圍(https://scotch.io/tutorials/理解範圍的,在JavaScript的)。你的變量是在'animatePoints'函數的範圍內定義的,而不是你的全局範圍。所以當你試圖從一個差異範圍引用它時,它不會被繼承到它,因爲它是未定義的。 –

回答

0

revealPoint在animatePoints的函數範圍中定義,而不是在for循環中調用的位置。

+0

謝謝羅素。這導致我的答案。 –

0

在哪個執行上下文中未定義? revealPoint似乎只是在animatePoints的上下文中定義的。它只能從該函數中訪問,並不會從那裏返回。

0

VAR animatePoints =功能(點){

VAR revealPoint =函數(指數){

   points[index].style.opacity = 1; 
       points[index].style.transform = "scaleX(1) translateY(0)"; 
       points[index].style.msTransform = "scaleX(1) translateY(0)"; 
       points[index].style.WebkitTransform = "scaleX(1) translateY(0)"; 

      } 
       for (i = 0; i < points.length; i++) 
      { 
       revealPoint(i); 
      } 
     }; 
相關問題