2013-05-08 91 views
0

当用户打开我的网站时,我的屏幕上有一个信息框(div)。只要用户向下滚动并且该框对用户不再可见,我希望该框在滚动时始终显示在右上角。在滚动后不再显示DIV,总是显示一个DIV?

我知道如何让它始终可见(position:fixed)。问题是,我怎么知道它何时对用户不可见并且在滚动时更多?如果有帮助,我也可以使用JavaScript。 Id更喜欢Prototype JS。

谢谢!

+0

基于scrollTop属性,您可以确定位置是否应该固定。 – 2013-05-08 12:56:04

回答

1

您需要使用getBoundingClientRect(),它返回元素相对于视口的位置。如果top的值低于0,那么它应该是固定的。

HTML:

<div id="stick"> 
    I should be fixed… sometimes 
</div> 

CSS:

#stick { 
    position: absolute; 
    top: 60px; 
} 

#stick.fixed { 
    position: fixed; 
    top: 0; 
} 

JS:

var stick = document.getElementById('stick'); 

window.onscroll = function(){ 
    if(stick.getBoundingClientRect().top < 0){ 
     stick.className = 'fixed'; 
    } else if(stick.className.indexOf('fixed') < 0){ 
     stick.className = ''; 
    } 
} 

Here's a demo