Home > Web Front-end > JS Tutorial > Simple implementation code for sidebar scrolling_javascript skills

Simple implementation code for sidebar scrolling_javascript skills

WBOY
Release: 2016-05-16 17:40:19
Original
1143 people have browsed it

When browsing websites, I often see that on some websites, some content in the side column is fixed at that position after scrolling to the top of the page, and no longer scrolls with the scroll bar. This effect is called "sidebar scrolling." It's useful for content that you don't want to scroll off the page.
There are many ways to implement sidebar scrolling. There are two common ones. These two methods are clearly introduced in an article written by NEOEASE. One is to use jQuery. Implementation, this method is obviously a burden for those websites that usually do not need to load the jQuery library (jQuery is getting bigger and bigger now...). Another method is to write the effect through native javascript. This method is much lighter than the previous one. However, I am still not satisfied. The files written by native JavaScript are more than 4K, which is still too complicated for someone like me who puts simplicity first. So is there a simpler way to implement it?

The answer is of course yes. Details are introduced below.
Let’s talk about the html file first (of course it can also be a dynamic file, there is always html code in it)

Copy the code The code is as follows:



Add content that needs to be scrolled here



Then the CSS code
Copy code The code is as follows:

#box{float:left; position:relative;width:250px;}
.div1{width:250px;}
.div2{position: fixed;_position:absolute;top:0;z-index:250;}

Finally is the JS code (can be placed in the page that needs to be scrolled, or in a separate JS file) Call)
Copy code The code is as follows:

(function(){
var oDiv =document.getElementById("float");
var H=0,iE6;
var Y=oDiv;
while(Y){H =Y.offsetTop;Y=Y.offsetParent};
iE6=window.ActiveXObject&&!window.XMLHttpRequest;
if(!iE6){
window.onscroll=function()
{
var s=document.body.scrollTop||document. documentElement.scrollTop;
if(s>H){oDiv.className="div1 div2";if(iE6){oDiv.style.top=(s-H) "px";}}
else{oDiv. className="div1";}
};
}
})();

OK, you're done, simple enough.
Finally give me an example.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template