scrollspy.min.js 1.7 KB

1
  1. !function(a,b){"function"==typeof define&&define.amd?define([],function(){return a.ScrollSpy=b()}):"object"==typeof exports?module.exports=b():a.ScrollSpy=b()}(this,function(){function a(a,b){var c=document;this.wrapper=c.querySelector(a),this.nav=this.wrapper.querySelectorAll(b.nav),this.contents=[],this.win=window,this.body=c.body,this.winH=this.win.innerHeight,this.className=b.className,this.callback=b.callback,this.init()}return a.prototype.init=function(){this.contents=this.getContents(),this.attachEvent()},a.prototype.getContents=function(){for(var a=[],b=0,c=this.nav.length;c>b;b++){var d=this.nav[b].href;a.push(document.getElementById(d.split("#")[1]))}return a},a.prototype.attachEvent=function(){this.win.addEventListener("load",function(){this.spy(this.callback)}.bind(this));var a;this.win.addEventListener("scroll",function(){a&&clearTimeout(a);var b=this;a=setTimeout(function(){b.spy(b.callback)},10)}.bind(this));var b;this.win.addEventListener("resize",function(){b&&clearTimeout(b);var a=this;b=setTimeout(function(){a.spy(a.callback)},10)}.bind(this))},a.prototype.spy=function(a){var b=this.getElemsViewState();this.markNav(b),"function"==typeof a&&a(b)},a.prototype.getElemsViewState=function(){for(var a=[],b=[],c=[],d=0,e=this.contents.length;e>d;d++){var f=this.contents[d],g=this.isInView(f);g?a.push(f):b.push(f),c.push(g)}return{inView:a,outView:b,viewStatusList:c}},a.prototype.isInView=function(a){var b=this.winH,c=this.body.scrollTop,d=c+b,e=a.offsetTop,f=e+a.offsetHeight;return d>e&&f>c},a.prototype.markNav=function(a){for(var b=this.nav,c=!1,d=0,e=b.length;e>d;d++)a.viewStatusList[d]&&!c?(c=!0,b[d].classList.add(this.className)):b[d].classList.remove(this.className)},a});