2013-09-22 41 views
1

我想用頭在頁面上顯示的通知,像這樣:滾動一個頭一個div,但保持它固定在20px的頂部時,頭消失

+-------------------------------+ 
| header      | 
+-------------------------------+ 
|    [notification] | 
| first line of my text   | 
| second line of my text  | 
:        : 

然而,當我向下滾動,通知應該滾動頁眉下方的頁面,但最大的地方是其top位於20px。所以,當我們滾動,視口應該保持這樣的:

| header      | 
+-------------------------------+ 
|    [notification] | 
| first line of my text   | 
| second line of my text  | 
:        : 

但最終,當標題開始從頁面上消失,我很好的頂上出現我的文字的通知,其top20px

+-------------------------------+ 
|    [notification] | 
| first line of my text   | 
| second line of my text  | 
|  third line of my text | 
:        : 

而且具有進一步滾動:

| first line of m[notification] | 
| second line of my text  | 
|  third line of my text | 
|   fourth line of my t | 
:        : 

所以基本上要顯示display: fixed; DIV與top: 20px,除了頁面最上面的

所以,當我第一次看到頁面的top屬性應該是在60px。但是,如果我向下滾動,我希望它的top始終在20px

我該如何做到這一點?

回答

1

只是爲了文檔的緣故,這裏有上Paranoid42的答案,這我接受片段:

CSS

.header { 
    height: 40px; 
    background-color: #3e8a94; 
} 

.notification { 
    position: fixed; 
    height: 20px; 
    right: 10px; 
    background-color: #3e55c7; 
    top: 50px; 
} 
.content { 
    padding:40px; 
    line-height: 20px; 
    height: 1000px; 
    border: 2px solid #666; 
} 

的JavaScript

window.addEventListener('scroll', function() { 
    if (document.body.scrollTop > 50) { 
    document.querySelector('.notification').style.top = '0px'; 
    } else { 
    document.querySelector('.notification').style.top = '50px'; 
    } 
}); 

HTML

<html> 
    <head></head> 
    <body> 
    <div class="notification"> notification</div> 
    <div class="header"></div> 
    <div class="content"><p> Lorem ipsum dolor sit amet, ..... </p></div> 
    </body> 
</html> 
相關問題