Home > Article > Web Front-end > jquery implements the div layer to scroll as the page scrolls
When browsing ipc.me, I feel that the slider on the right side will always float under the edge of the window as the page is turned down. The experience is very good. Based on an article in Zhang Xinxu’s blog, I successfully implemented such a function. The code is as follows (Based on jquery, so jquery files must be imported into the page in advance):
<script type="text/javascript"> $.fn.smartFloat = function() { var position = function(element) { var top = element.position().top, pos = element.css("position"); $(window).scroll(function() { var scrolls = $(this).scrollTop(); if (scrolls > top) { if (window.XMLHttpRequest) { element.css({ position: "fixed", top: 0 }); } else { element.css({ top: scrolls }); } }else { element.css({ position: "absolute", top: top }); } }); }; return $(this).each(function() { position($(this)); }); }; $("要浮动的层id或class").smartFloat(); </script>
Of course, it is under chrome. IE has not tested it, so it should be possible. The principle of implementation is as follows (it is best to take a look and understand the principle, just stop here Look at the problem from the commanding heights and see the mountains at a glance):
The default state is the default state. You don’t need to do anything. Whether the positioning is absolute or static, it is all OK. The key is that when the browser scrolls and the object (the layer to be floated) needs to be removed from the browser interface viewport, just modify its position attribute so that it floats and displays on the upper edge of the window. The best position attribute is fixed, which can smooth and fixed positioning of floating layers in IE6+ and other browsers. Since IE6 predecessors do not support the fixed attribute, so take a step back and use the absolute attribute instead, but there will be side effects - the scrolling will not be smooth. . However, there is nothing we can do about it.
The key now is how to determine whether the current layer is in contact with the upper edge of the browser window? When the floating layer comes into contact with the upper edge of the browser window, the vertical offset value of the page is actually the same as the scroll height of the page. Therefore, it is OK to use this to make a judgment. However, how to obtain the distance between the elements on the page and the page? What about vertical distance? It is still troublesome to obtain this value with pure js code. Fortunately, the JavaScript library jQuery helps us solve these tasks.