没有jQuery的粘性侧边栏javascript

时间:2013-06-16 17:01:45

标签: javascript css

如何制作带有塞子的粘性垂直侧边栏,但没有 jQuery?是否有任何片段/插件?我不需要它来支持旧浏览器。

我的意思不仅仅是位置:固定,它必须保持在同一个地方,然后当你滚动到某一点时开始变粘(固定)。然后必须在停止点停止跟踪。

喜欢http://stickyjs.com,但不是jQuery。有许多jQuery插件可用。

4 个答案:

答案 0 :(得分:6)

基本上它就像这样容易:

window.onscroll = function() {
    var sticky = document.getElementById('stickynav');
    if( document.body.scrollTop+document.documentElement.scrollTop > 240)
        sticky.className = "stuck";
    else sticky.className = "";
};

然后在.stuck类中定义样式,将position:fixed之类的内容添加到元素中。

答案 1 :(得分:3)

这是一次不需要position: fixed更改的尝试,使用元素文档距离作为参考,让你滚动到底部:

var node = document.getElementById('side'),  // your element
    nodeOffs = node.offsetTop,               // distance relative to its parent
    parent = node;

// loop through parents to determine the distance relative to the document top
while(parent = parent.offsetParent)
  if(parent.offsetTop)
    nodeOffs += parent.offsetTop;

window.addEventListener('scroll', function(event){    

  // current scroll position relative to the body
  var scrollPos = document.body.scrollTop;

  if(scrollPos > nodeOffs){

    // don't do anything if the elements height is larger than the
    // remaining scroll content height (distance including)
    if(scrollPos < (document.body.scrollHeight - node.clientHeight - nodeOffs))
      node.style.top = (scrollPos - nodeOffs) + 'px';

  }else{
      node.style.top = '0px';
  }

});    

这可能不会处理所有可能的情况(例如,它没有考虑边距)。这就是为什么有一个插件,你应该使用它,如果你不想自己调整js ....

(test)

答案 2 :(得分:1)

我知道这是一个古老的问题,并且它正在要求一个JavaScript解决方案,因为这里的主要思想是使粘性工具栏正常工作,我必须分享一个纯粹的CSS解决方案,该解决方案可以按预期工作:

.sticky {
    position: -webkit-sticky; /* Safari */
    position: sticky;
    top: 0;
}

只需将sticky类应用于您的侧边栏元素,它将起作用。

这肯定会为您节省很多时间和精力。

REF:https://developer.mozilla.org/es/docs/Web/CSS/position#sticky

答案 3 :(得分:0)

可以使用较短的JS来实现。

const stickyDiv = document.querySelector(".sticky");
window.addEventListener("scroll", function() {
  stickyDiv.style.top = window.pageYOffset + "px";
});
.left {
  position: relative;
}
.sticky {
  position: absolute;
}

  /* below is unecessary CSS just to demo the page */
.left {
  width:40%;
  float:left;
}
.right {
  width: 40%;
  min-height: 3000px;
  float:right;
}
<div class="container">
  <div class="row">
    
    <div class="left">
      <article class="sticky">
        <h2>Sticky sidebar title here</h2>
        <p>Text here</p>
      </article>
    </div>
    
    <div class="right">
      <article>
        <h2>Regular page here</h2>
        <img src="http://lorempixel.com/400/200/cats">
        <p>Regular page content here.</p>
      </article>
    </div>
    
  </div>
</div>

https://codepen.io/MistaPrime/pen/vYYxvza