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);
}
注意:一旦它的正常工作,我打算添加某種反跳和節流的。