滚动时如何在容器中粘贴div

时间:2014-10-02 03:01:53

标签: jquery html css

我希望达到这种效果,当用户向下滚动#cart时会粘在屏幕上并仅保留在div.container。像下面的东西。我尝试使用固定的位置,但向下滚动#cart时不能粘在容器div内。我应该考虑jQuery这个效果吗?

enter image description here

HTML

<header>Header</header>
<div id="container">
    <div id="cart">Cart
        <p>1x MacBook Air</p>
        <p>1x iPhone</p>
        <p>1x iPod</p>
    </div>
</div>
<footer>Footer</footer>

CSS

header {
   width: 400px;
   height: 100px;
   background-color: #ddd;
   margin: 0 auto;
}
#container {
  background-color: #aeaeae;
  height: 1000px;
  margin: 0 auto;
  position: relative;
  width: 400px;
}
#cart {
  border: 2px solid #000;
  position: absolute;
  right: 0;
  top: 100px;
  width: 100px;
}
footer {
   width: 400px;
   height: 100px;
   background-color: #ddd;
   margin: 0 auto;
}

演示jsfiddle

4 个答案:

答案 0 :(得分:1)

我认为你要找的是:

StickyMojo 要么 jQuery Stickem

Bootstrap有类似的东西,名为Affix

答案 1 :(得分:0)

position:fixed会奏效。您只需要将容器div移动到容器div之外。

答案 2 :(得分:0)

固定定位是基于文档的,因此当用户滚动时将固定到整个窗口。您无法修复位置并且位于容器内。你必须带#cart来解决它。

要使它粘在容器内但又固定是矛盾的。

如果您希望它保持固定,但是当它向下滚动到容器的底部时,它会向下滚动到远处,所以它只是触及容器的底部并保持在里面 - 这就是一个jquery工作。如果那就是你想要的,我可以帮忙吗?

答案 3 :(得分:0)

您希望position: fixed;元素上有#cart,并且您可能需要一些Javascript才能使其与容器保持正确对齐。

Fiddle