2014-10-02 53 views
-1

我想实现这种效果,当用户向下滚动时,#cart将会粘在屏幕上并仅保留在div.container中。像下面的东西。我尝试使用固定的位置,但向下滚动时#cart不能粘在容器格内。我应该考虑jQuery的这种效果吗?滚动时如何在容器中粘贴div

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

+0

位置:固定将只停留在页面内,如您所见。我认为jQuery是最好的选择。我想不出一种只用CSS来完成的方法。 – coopersita 2014-10-02 03:11:41

回答

0

position:fixed会工作。您只需将容器格外的购物车格移动即可。

0

固定位置是基于文档的,因此当用户滚动时会固定到整个窗口。你不能固定位置,并在容器内。你必须拿#出去解决它。

为了让它粘在容器内但固定也是矛盾的。

如果您希望它保持固定,但是一旦它滚动到容器的底部时,就会触及容器的底部并停留在内部 - 这是一项jQuery工作。如果这就是你想要的,我可以帮忙吗?

0

你想在#cart元素上使用position: fixed;,你可能需要一些Javascript来保持它与容器的右对齐。

Fiddle