Simple implementation code for sidebar scrolling_javascript skills
May 16, 2016 pm 05:40 PMWhen 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)
<div id="box">
<div id="float" class="div1">
Add content that needs to be scrolled here
</div>
</div>
Then the CSS code
#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)
(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.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to implement scrolling to a specified element position in JavaScript?

HTML, CSS, and jQuery: Make an auto-scrolling bulletin board

How to use JavaScript to achieve the infinite scroll effect of automatically loading when scrolling to the bottom of the page?

How to implement scrolling switching effect of images in JavaScript?

How to implement full screen scrolling effect in Vue

How to achieve smooth scrolling to the bottom button with CSS

How to use JavaScript to achieve the highlight effect of scrolling the navigation menu to a specified position?
