2016-03-21 11 views
0

Yapmaya çalıştığım şey tüm 'bölüm' öğelerini bulmaktır, hangisinin viewportta olduğunu algılamak ve geçerli bölüme className uygulamaktır. Görünüm dışında kaydırırken className yeniden kaldırılmalıdır.Görünüm içinde hangi öğenin olduğunu algıla ve sınıfı uygula

İşte temel bilgiler.

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

} 

Not: Düzgün çalışan bir kere, ben gürültüye ve throttler çeşit eklemeyi planlıyoruz ben Eklentinin tüm yöntemleri ve işlevleri dahil değil, sadece gerekli neyin soruya cevap yardımcı olmak.

cevap

0

bana atlar Bu immmediate şey: bu yanlıştır:

if (section._isInViewport) { 

_isInViewport şöyle bir argüman olarak içinde eleman geçmek gerekir:

if (_isInViewport(section)) { 

Ayrıca don' Olay işleyicisinde olay tipini kontrol etmemiz gerekir. Bunu yalnızca kaydırmada aradığınızdan beri, etkinlik türünün bir kaydırma olayı olduğunu zaten biliyorsunuz. Yerine şey:

_getSections(); 
:

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

Bunu istiyorsun

İlgili konular