Javascript 检测视口中的元素并应用类

Javascript 检测视口中的元素并应用类,javascript,Javascript,我要做的是找到所有的“section”元素,检测视口中的哪个元素,并将类名应用到当前节。滚动出视口时,应再次删除类名 这里是基本的。我还没有包括插件的所有方法和功能,只是需要什么来帮助回答这个问题: // A simple forEach() implementation for Arrays, Objects and NodeLists. // By Todd Motto var forEach = function (collection, callback, scope) { if

我要做的是找到所有的“section”元素,检测视口中的哪个元素,并将类名应用到当前节。滚动出视口时,应再次删除类名

这里是基本的。我还没有包括插件的所有方法和功能,只是需要什么来帮助回答这个问题:

// 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);

}
//一个用于数组、对象和节点列表的简单forEach()实现。
//托德座右铭
var forEach=函数(集合、回调、作用域){
if(Object.prototype.toString.call(collection)='[Object Object]'){
for(集合中的var prop){
if(Object.prototype.hasOwnProperty.call(collection,prop)){
callback.call(作用域,集合[prop],prop,集合);
}
}
}否则{
for(var i=0,len=collection.length;i=0&&
rect.left>=0&&

rect.bottom这个向我跳出来的中间事物:这是错误的:

if (section._isInViewport) {
\u isInViewport
要求您将元素作为参数传入,如下所示:

if (_isInViewport(section)) {
您也不需要检查事件处理程序中的事件类型。因为您只在scroll上调用它,所以您已经知道事件类型是scroll事件。而不是:

if (event.type === 'scroll') {
    _getSections();
}
你想要这个:

_getSections();