2015-10-20 136 views
2

我是html和css的新手,我想知道這是否可以在純CSS中使用。更改固定css元素的「起始位置」

所以我製作了3個div,全部完全符合我的屏幕尺寸。我想知道的是,如果你讓「菜單」固定,讓它滾動,你能改變它的起始位置嗎?

<div class="red"></div> 
<div class="blue"> 
    <h1>Menu</h1> 
</div> 
<div class="green"></div> 

這是與它一起去的CSS:

.red{ 
    background-color: red; 
    width: 100%; 
    height: 1080px; 
} 

.blue{ 
    background-color: blue; 
    width: 100%; 
    height: 1080px; 
} 

.green{ 
    background-color: green; 
    width: 100%; 
    height: 1080px; 
} 


h1{ 
    font-size: 100px; 
    position: fixed; 
    top: 0; 
} 

所以我基本上的意思是可以通過「菜單」當我從滾動越過藍格,向下,同時它的不可見的固定但在紅色的div? (所以它的'起始位置'實際上是在藍色的div上)

對不起,如果問題解釋不好,英語不是我的母語。先謝謝你。

+0

你的意思是說,一旦滾動的藍色div出現,菜單跳轉到它並離開紅色的div? –

+0

我的意思是'菜單'會出現藍色div等等,但是當你回滾到紅色的div時,它會再次堅持藍色,所以當頁面加載時,'menu'將不會可見,直到出現藍色的div。 –

+0

你想讓菜單隻出現在藍色區域,對吧? –

回答

0

我知道你提到你想在純CSS中的解決方案,但如果你想使用JQuery這將是一個解決方案。

使菜單絕對:

.persist-menu 
{ 
    position: absolute; 
} 

權的功能更新菜單

function UpdateMenuPosition() { 
     var el    = $(".blue"), 
      offset   = el.offset(), 
      scrollTop  = $(window).scrollTop(), 
      floatingHeader = $(".persist-menu", el) 

     if (scrollTop > offset.top) { 
      floatingHeader.css({top:(scrollTop)}); 
     } else { 

     }; 
} 

的位置,並調用它,而滾動

$(function() { 

    $(window) 
    .scroll(UpdateMenuPosition) 
    .trigger("scroll"); 

}); 

檢查演示:http://jsfiddle.net/wfff74w9/4/

+0

這就是我一直在尋找的,謝謝。但是,我還不知道如何將JQuery加載到我的html文檔中。 –

+0

歡迎您:)您可以從這裏下載jquery文件[下載](http://jquery.com/download/) 然後將此標籤添加到您的html標頭中' ' –

+0

非常感謝您的幫助!我知道我現在聽起來可能聽起來很愚蠢,但我是否會將代碼複製到HTML中的腳本標記中,或者將腳本保存爲.js文件嗎? –

1

您可以使用z-index在紅色和綠色div上隱藏「菜單」。

CSS:

.red{ 
background-color: red; 
width: 100%; 
height: 1080px; 
z-index:3; 
position: relative; 
} 
.blue{ 
background-color: blue; 
width: 100%; 
height: 1080px; 
z-index:1; 
} 
.green{ 
background-color: green; 
width: 100%; 
height: 1080px; 
z-index:3; 
position: relative; 
} 
h1{ 
font-size: 100px; 
position: fixed; 
top: 0; 
z-index:2; 
} 

例子:http://jsfiddle.net/3k3wyscL/

但這種解決方案有問題是添加其他文本只紅色或綠色的div可見。

編輯:你也可以在綠色div上看到「Menu」,你可以在css中刪除綠色的z-index和位置參數。