usage
You pass in the Selector that you want to animate, and you implement a custom scroll animation based on the in-view and out-view that you add
new ScrollMotion('.motion');
Copy the code
The core
/ * * *@param {String} Selector The element selector that requires animation *@param {number} Threshold Indicates whether to advance or lag the threshold. Positive value: indicates that the threshold pixel appears in advance; negative value: indicates that the threshold pixel appears in advance
var ScrollMotion = function (selector, threshold) {
var _motionSelf = this;
this.motionEls = document.querySelectorAll(selector);
this.threshold = threshold ? threshold : 50;
function scrollAnimation() {
_motionSelf.motionEls.forEach(element= > {
if (domInView(element)) {
element.classList.remove('out-view');
element.classList.add('in-view');
} else {
element.classList.remove('in-view');
element.classList.add('out-view'); }}); }// Whether it is in the viewport
function domInView(element) {
var viewHeight = window.innerHeight || document.documentElement.clientHeight; // Height of visible area
elementRectTop = element.getBoundingClientRect().top;
return elementRectTop + _motionSelf.threshold <= viewHeight;
};
scrollAnimation();
window.addEventListener('scroll', scrollAnimation);
}
Copy the code
Expand & Optimize
- To process the parameters passed in, support passing selector /node/nodeList
// new ScrollMotion(target);
function getMotionElements(target) {
var elements = [];
if (typeof target === 'string') {
elements = [].slice.call(document.querySelectorAll(target), 0);
} else {
if (isElement(target)) {
elements = [target];
}
if (target && target.length > 0) {
elements = [].slice.call(target, 0); }}return elements;
};
function isElement(obj) {
return!!!!! (obj && obj.nodeType ===1);
};
Copy the code
- Add throttling function
- Set two threshold parameters (threshold) for entry and exit timing control