2016-03-21 36 views
0

我想要做的是找到所有'節'元素,檢測哪一個在視口中並將className應用於當前節。滾動出視口時應該再次移除className。檢測哪個元素在視口中並應用類

以下是基本知識。我還沒有包括該插件的所有方法和功能,只是什麼需要幫助回答問題:

// A simple forEach() implementation for Arrays, Objects and NodeLists. 
// By Todd Motto 
var forEach = function (collection, callback, scope) { 
    if (Object.prototype.toString.call(collection) === '[object Object]') { 
     for (var prop in collection) { 
      if (Object.prototype.hasOwnProperty.call(collection, prop)) { 
       callback.call(scope, collection[prop], prop, collection); 
      } 
     } 
    } else { 
     for (var i = 0, len = collection.length; i < len; i++) { 
      callback.call(scope, collection[i], i, collection); 
     } 
    } 
}; 

// Determine if an element is the viewport or not 
var _isInViewport = function (elem) { 
    var rect = elem.getBoundingClientRect(); 
    return (
     rect.top >= 0 && 
     rect.left >= 0 && 
     rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && 
     rect.right <= (window.innerWidth || document.documentElement.clientWidth) 
    ); 
}; 

// Get all sections and 
var _getSections = function() { 

    var sections = document.querySelectorAll('section'); 

    forEach(sections, function (section) { 

     if (section._isInViewport) { 
      section(_isInViewport).classList.add('section-is-in-view'); 
      alert('yest'); 
     } else { 
      section(_isInViewport).classList.remove('not-in-view'); 
     } 

    }); 

}; 


// The event handler 
var _eventHandler = function (event) { 

    if (event.type === 'scroll') { 
     _getSections(); 
    } 

}; 


// Initialise the plugin 
plugin.init = function (options) { 

    // Listen for scroll events and run event handler 
    document.addEventListener('scroll', _eventHandler, false); 

} 

注意:一旦它的正常工作,我打算添加某種反跳和節流的。

回答

0

這是我跳出immmediate的事情:這是錯誤的:

if (section._isInViewport) { 

_isInViewport需要你的元素作爲參數傳遞,就像這樣:

if (_isInViewport(section)) { 

你也不要」需要檢查事件處理程序中的事件類型。既然你只是在滾動上調用它,你已經知道事件類型是一個滾動事件。而不是事情:

if (event.type === 'scroll') { 
    _getSections(); 
} 

你想這樣的:

_getSections(); 
相關問題