Javascript sticky div after scroll

匆匆过客 提交于 2019-12-03 15:25:20

CSS

#left {
  float:left;
  width:100px;
  height:200px;
  background:yellow;
  margin:200px 0 0;
}
#left.stick {
  position:fixed;
  top:0;
  margin:60px 0 0
}

added a stick class, so javascript doesn't have to do too much work.

JS

    // set everything outside the onscroll event (less work per scroll)
var left      = document.getElementById("left"),
    // -60 so it won't be jumpy
    stop      = left.offsetTop - 60,
    docBody   = document.documentElement || document.body.parentNode || document.body,
    hasOffset = window.pageYOffset !== undefined,
    scrollTop;

window.onscroll = function (e) {
  // cross-browser compatible scrollTop.
  scrollTop = hasOffset ? window.pageYOffset : docBody.scrollTop;

  // if user scrolls to 60px from the top of the left div
  if (scrollTop >= stop) {
    // stick the div
    left.className = 'stick';
  } else {
    // release the div
    left.className = ''; 
  }
}

WORKING JSFIDDLE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!