2013-07-10 119 views
0

我需要創建一個橫幅的佔位符,它需要與頁面一起向上滾動,直到它到達瀏覽器的頂部邊緣,然後它應該固定在頂部。當頁面向下滾動時,橫幅也需要再次滾動頁面。我不確定我是否足夠清晰,因此您可以在Watch Critic處看到示例。您會注意到右欄中的橫幅行爲與我所描述的相同。使用HTML和CSS滾動頁面的固定橫幅

我沒有JavaScript經驗,所以只能通過HTML和CSS來實現嗎?

+0

posible dub http://stackoverflow.com/questions/13795283/fixed-header-while-scroll – koningdavid

+0

看這裏http://stackoverflow.com/questions/8644248/jquery-fix-div-when-browser-滾動到它 – Majky

回答

0

活生生的例子:http://jsfiddle.net/KXXhQ/

你需要利用scroll事件的jQuery,然後添加一個新的類,你的頭,以解決它:

jQuery的

//by default, the static menu is hidden 
    var showStaticMenuBar = false; 

    //when scrolling... 
    $(window).scroll(function() { 

     //if the static menu is not yet visible... 
     if (showStaticMenuBar == false) { 
      //if I scroll more than 200px, I show it 
      if ($(window).scrollTop() >= 200) { 
       //showing the static menu 
       $('#header').addClass('fixed'); 

       showStaticMenuBar = true; 
      } 
     } 
     //if the static menu is already visible... 
     else { 
      if ($(window).scrollTop() < 200) { 
       $('#header').removeClass('fixed'); 

       //I define it as hidden 
       showStaticMenuBar = false; 
      } 
     } 
    }); 

CSS

#header{ 
    display:block; 
    width: 100%; 
    height:50px; 
    background: #ddff00; 
} 
#header.fixed{ 
    position:fixed; 
    top: 0; /*fixing it at the top*/ 
    z-index: 999; /* over any other element*/ 
} 

活生生的例子:http://jsfiddle.net/KXXhQ/

0

This是你可以設置固定在CSS的位置。如果你想獲得更多的行爲,你可以將它們定義爲CSS類,當你需要改變行爲時,只需使用jQuery添加和刪除類。