1. Application display
About the smart floating effect of layers. I saw it on the vertical navigation of some personal websites abroad a few years ago, and now it seems to be on some domestic commercial websites. This effect is also seen frequently, such as the sorting horizontal bar on Taobao's search results page. In the default state, the scroll bar scrolls with the page, as follows:
As the page scrolls down, when the horizontal bar touches the upper edge of the browser, the horizontal bar becomes independent and does not scroll with the scroll bar, as shown in the following figure:
Similar effects are also available on Sina Weibo:
When the page scrolls and the new dynamic prompt begins to fade out of the browser window, it floats on the top edge of the browser window, as shown in the figure below:
The principle of realizing this effect is actually very simple, and this article will show its implementation.
2. Implementation Principle
The default state is the default state. You don’t need to do anything. Whether the positioning is absolute or static, it is 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 that can be done 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 helps us solve these tasks, so our work is actually very smooth. The following will show how to achieve this effect under the jQuery library and the MooTools library.
3. Smart floating of layers under jQuery
The method code is as follows: