In fact, this effect can be seen on many websites, mainly as floating ads on both sides of the web page. It may seem difficult to do, but the principle is actually very simple. Use a timer to detect the position of the layer every 0.1 seconds and place it at the specified position (relative to the window). Wrote a simple code:
If you need to introduce external Js, you need to refresh to execute ]
Note:
if (window.innerHeight) {
posX = window.pageXOffset;
posY = window.pageYOffset;
}
else if (document.documentElement && document. documentElement .scrollTop) {
posX = document.documentElement.scrollLeft;
posY = document.documentElement.scrollTop;
}
else if (document.body) {
posX = document.body. scrollLeft;
posY = document.body.scrollTop;
}
This code is for standard compatibility. In the xhtml page, document.body.scrollTop is always 0, that is, the attribute is invalid, so it must be used To judge other attributes, in order to be compatible with old and new standards, the availability of attributes should be judged.
Quoting a text from the Internet:
Quoting
Applying WEB standards will invalidate the ScrollTop attribute! ! !
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional .dtd">
After adding this paragraph, document.body.scrollTop will always be equal to 0
body onscroll = "alert(document.body.scrollTop);" will never be triggered.
Solution:
Use:
document.documentElement.scrollTop
Example 1:
var scrollPos;
if (typeof window.pageYOffset != 'undefined') {
scrollPos = window.pageYOffset;
}
else if (typeof document.compatMode != 'undefined' &&
document.compatMode != 'BackCompat') {
scrollPos = document.documentElement.scrollTop;
}
else if (typeof document.body != 'undefined') {
scrollPos = document.body.scrollTop;
}
alert(scrollPos);
Example 2:
function WebForm_GetScrollX()
{
if (__nonMSDOMBrowser)
{
return window.pageXOffset;
}
else
{
if (document.documentElement && document.documentElement.scrollLeft)
{ return document.documentElement.scrollLeft;
>}
----------------------------------------
pageYOffset is from netscape
document.body.scrollTop and document.documentElement.scrollTop are for IE, but I don’t know their real difference. I only know that documentElement.scrollTop is xhtml compatible (I use strict)