2013-05-08 92 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