jquery - 向上滚动时粘性侧边栏 : stick to bottom when scrolling down, 顶部

标签 jquery position fixed sidebar sticky

我一直在寻找解决粘性边栏问题的方法。我对我希望它如何行动有一个具体的想法;实际上,我希望它在您向下滚动时粘在底部,然后一旦您向上滚动,我希望它以流畅的运动(不跳跃)粘在顶部。我无法找到我想要实现的目标的示例,因此我创建了一张图片,希望能更清楚地说明这一点:

Sticky sidebar: stick to bottom when scrolling down, top when scrolling up

  1. 侧边栏位于标题下方。
  2. 当您向下滚动时,侧边栏与页面内容保持水平,以便您可以滚动浏览侧边栏和内容。
  3. 到达侧边栏的底部,侧边栏会粘在视口(viewport)的底部(大多数插件只允许粘在顶部,一些允许粘在底部的插件不允许同时粘在底部)。
  4. 到达底部,边栏位于页脚上方。
  5. 当您向上滚动时,侧边栏与内容保持水平,因此您可以再次滚动浏览内容和侧边栏。
  6. 到达侧边栏的顶部,侧边栏粘在视口(viewport)的顶部。
  7. 到达顶部,边栏回到标题下方。

我希望这是足够的信息。我已经创建了一个 jsfiddle 来测试任何插件/脚本,我已经为这个问题重置了它:http://jsfiddle.net/jslucas/yr9gV/2/ .

最佳答案

+1 非常漂亮且具有说明性的图像。

我知道这是一个老问题,但我偶然发现了你在forum.jquery.com 中发布的相同问题。那里有一个答案 (by@tucker973),推荐了一个很好的库来制作这个并想在这里分享。

它被 @leafo 称为 sticky-kit

这里有我准备的一个非常基本的示例的代码和一个用于查看结果的工作演示。

/*!
 * Sticky-kit
 * A jQuery plugin for making smart sticky elements
 *
 * Source: http://leafo.net/sticky-kit/
 */

$(function() {
  $(".sidebar").stick_in_parent({
    offset_top: 10
  });
});
* {
  font-size: 10px;
  color: #333;
  box-sizing: border-box;
}
.wrapper,
.header,
.main,
.footer {
  padding: 10px;
  position: relative;
}
.wrapper {
  border: 1px solid #333;
  background-color: #f5f5f5;
  padding: 10px;
}
.header {
  background-color: #6289AE;
  margin-bottom: 10px;
  height: 100px;
}
.sidebar {
  position: absolute;
  padding: 10px;
  background-color: #ccc;
  height: 300px;
  width: 100px;
  float: left;
}
.main {
  background-color: #ccc;
  height: 600px;
  margin-left: 110px;
}
.footer {
  background-color: #6289AE;
  margin-top: 10px;
  height: 250px;
}
.top {
  position: absolute;
  top: 10px;
}
.bottom {
  position: absolute;
  bottom: 10px;
}
.clear {
  clear: both;
  float: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://leafo.net/sticky-kit/src/jquery.sticky-kit.js"></script>
<div class="wrapper">
  <div class="header"> <a class="top">header top</a>
    <a class="bottom">header bottom</a>

  </div>
  <div class="content">
    <div class="sidebar"> <a class="top">sidebar top</a>
      <a class="bottom">sidebar bottom</a>

    </div>
    <div class="main"> <a class="top">main top</a>
      <a class="bottom">main bottom</a>

    </div>
    <div class="clear"></div>
  </div>
  <div class="footer"> <a class="top">footer top</a>
    <a class="bottom">footer bottom</a>

  </div>
</div>

当然,所有的功劳归功于插件的创建者,我只做了这个例子来展示它。我需要完成与您相同的结果,并且发现这个插件非常有用。

关于jquery - 向上滚动时粘性侧边栏 : stick to bottom when scrolling down, 顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18358816/

相关文章:

html - 无法移动#element1,这是为什么?

java - 如何在 GWT 中设置固定位置面板?

javascript - 如何在 Bootstrap TreeView 中按ID选择节点?

jquery - 在 Windows Phone 8 上的 IE 10 上滚动时网页闪烁

html - 显示在线校正

html - CSS 工具提示不会拉伸(stretch),只能有固定宽度

jquery - 当页面内点击内容较少时修复页脚

html - 在 Safari 中使用固定位置时文本被覆盖

javascript - HTML 列表,添加 JQuery 以交叉选择的项目。

javascript - 单击链接时获取链接的 ID