varjquery = require ("jquery");(function($) {JQuery.fn.scrollFix=function(height, dir) {height= Height | | 0; Height= height = = "Top"? 0: Height; return This. each (function() { if(height = = "Bottom") {Height= Document.documentElement.clientHeight- This. scrollheight; } Else if(Height < 0) {Height= Document.documentElement.clientHeight- This. scrollheight +height; } varthat = $ ( This), OldHeight=false, P, R, L=That.offset (). Left; Dir= Dir = = "Bottom"? Dir: "Top";//default scrolling direction down if(Window. XMLHttpRequest) {//fixed for non-IE6 functionGetHeight () {//>=0 indicates that the above scrolling height is greater than or equal to the target height return(Document.documentElement.scrollTop | | document.body.scrollTop) + height-That.offset (). Top; } $ (window). Scroll (function() { if(OldHeight = = =false) { if((getheight () >= 0 && dir = = "Top") | | (getheight () <= 0 && dir = = "Bottom") ) {OldHeight= That.offset (). Top-height; That.css ({position:"Fixed", Top:height, left:l}); } } Else { if(dir = = "Top" && (Document.documentElement.scrollTop | | document.body.scrollTop) <oldheight) {That.css ({position:"Static" }); OldHeight=false; } Else if(dir = = "Bottom" && (Document.documentElement.scrollTop | | document.body.scrollTop) >oldheight) {That.css ({position:"Static" }); OldHeight=false; } } }); } Else{//For IE6$ (window). Scroll (function() { if(OldHeight = = =false) {//perform only once before recovery, reducing reflow if((getheight () >= 0 && dir = = "Top") | | (getheight () <= 0 && dir = = "Bottom") ) {OldHeight= That.offset (). Top-height; R= Document.createelement ("span"); P= That[0].parentnode; P.replacechild (R, that[0]); Document.body.appendChild (that[0]); that[0].style.position = "Absolute"; } } Else if(dir = = "Top" && (Document.documentElement.scrollTop | | document.body.scrollTop) < oldheight) | | (dir = = "Bottom" && (Document.documentElement.scrollTop | | document.body.scrollTop) > OldHeight)) {//EndThat[0].style.position = "Static"; P.replacechild (that[0], R); R=NULL; OldHeight=false; } Else{//scrollingthat.css ({left:l, top:height+Document.documentElement.scrollTop})}); } }); };}) (jQuery);
Calling methods
$ ("#nav"). Scrollfix ("top");
Non-compliant compact version
varPosition = $ ('. Pub-banner '). Height () + $ ('. Wgt-searchbar '). Outerheight ();//the position of the element above it,$ (window). On (' scroll ',function() {console.log (position); //Console.log ($ (window). scrolltop ()); if($ (window). scrolltop () >position) { //alert (' 1 ');$ (' #nav '). css ({' Position ': ' Fixed ', ' Top ': ' 0 ' }); } Else { $(' #nav '). css ({' Position ': ' Static ', }); }});
Fixed position with height