简体   繁体   中英

How to stick div on top of the page

I just want to stick the div on top of the page

if someone scrolls the page then the green div stickdiv should be automatically stick in the top

var left = document.getElementsByClassName("stickdiv");

for( var i = 0;i<left.length;i++){
var stop = (left[0].offsetTop);

window.onscroll = function (e) {
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
    if (scrollTop >= stop) {
     left.className += " stick"; //adding a class name
    } else {
        className = '';
    }

}
}

why adding stick class on the div does not working - https://jsfiddle.net/kzk5qab2/1/

I just want to stick the div at top like yellow div on this - http://jsfiddle.net/qc4NR/

You have looped into the array of left items, but forget to reference the array index when trying to add the class name to the element.

 var left = document.getElementsByClassName("stickdiv"); for (var i = 0; i < left.length; i++) { var stop = (left[0].offsetTop); window.onscroll = function(e) { var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; // left.offsetTop; if (scrollTop >= stop) { // get array item by index left[0].classList.add('stick'); //adding a class name } else { // get array item by index left[0].classList.remove('stick'); } } } 
 .stickdiv { height: 50vh!important; width: 100vh!important; background-color: green!important; } .stick { position: fixed; top: 0; margin: 0 0 } #right { float: right; width: 100px; height: 1000px; background: red; } .des { height: 300px; width: 100%; background-color: #000; } 
 <div class="des"></div> <div class="stickdiv"></div> <div id="right"></div> 

You don't even need to loop if you select the item directly, as in the following:

var left = document.querySelector(".stickdiv");
var stop = (left.offsetTop);

window.onscroll = function(e) {
  var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
  // left.offsetTop;
  if (scrollTop >= stop) {
    left.classList.add('stick'); //adding a class name
  } else {
    left.classList.remove('stick');
  }
}

Depending on what browsers you need to support, you don't necessarily need JS for this.

.sticky {
    position: sticky;
    left: 0;
    top: 0;
    width: 100%;
}

Codepen: https://codepen.io/afisher88/pen/xJaxoP

Browser support for position sticky: https://caniuse.com/#search=position%3A%20sticky

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM