2013-07-15 154 views
1

我正在處理打破默認頁面功能的頁面。它的工作原理是這樣的:固定元素的設置高度

一旦你第一次開始滾動頁面,當背景和飛濺被修復時,一個閃屏的畫面會逐漸消失,一旦你有了像2400px之類的東西,滾動開始表現爲正常。這是我正在處理的解決方案:

<div class="wrapper"> 
    </p>Rest of the content</p> 
</div> 
<div class="splash" > 
    <p>Splash-content that has 100% height and width</p> 
</div> 

一旦你加載頁面,兩個div:s被設置爲位置固定。然後,我會根據頁面滾動的距離來監聽滾動事件並設置不透明度。一旦頁面滾動到目前爲止,以便飛濺具有不透明度:0,我將包裝設置爲顯示:static和margin-top:2400,以轉換爲正常的滾動行爲。 (這是使用以下addClass(fixed)完成

$(document).scroll(function(){ 
    var scrolllength = parseInt($(window).scrollTop()); 
    switch(true) { 


     //y2004 starts to show 
     case (scrolllength > y2004): 
      console.log('above 2004 bottom') 
      $('.wrapper').removeClass('fixed'); 
      break; 


     //y2003 is fully visible 
     case (scrolllength > y2003bottom): 
      console.log('below 2003 bottom') 
      $('.wrapper').addClass('fixed') 

      $('.splash').css('display','none'); 
      $('.text').fadeIn('fast'); 

      break; 

     //scrolling up, splash starts to show again 
     case (scrolllength < y2003bottom && scrolllength > 0): 
      console.log('above 2003 bottom '+scrolllength) 
      var splashopacity = ((y2003bottom -scrolllength)/y2003bottom); 
      $(".splash").css('opacity',(splashopacity)); 
      //show the splash again 
      $('.splash').css('display', 'block'); 
      $('.text').fadeOut('fast'); 
      break; 


     //default 
     default: 
      console.log(scrolllength); 
      return; 
    } 
}); 

固定CSS: .fixed { 位置是:固定; 頂部:0; 寬度:100%; 邊距:0; }。

這種方法運行良好,唯一的問題是,當我將包裝器設置爲「固定」時,它會丟失高度,這反過來又使得不能滾動,我希望文檔根據內容來擴大窗口大小.wrapper。或者任何其他解決方案實現類似的目標.Css是首選​​,但JavaScript也很好!

+0

可能的重複:http://stackoverflow.com/questions/5102395/css-positionabsolute-dynamic-height(與谷歌發現爲第1打正着:動態大小的CSS固定元素) –

+0

我不使用的位置是:絕對,但是是靜態的。我要去看看那個奇怪的事情,但我不認爲它會對我有所幫助,謝謝你! – Himmators

+0

我創建了一個新的問題,這是希望一個更清楚一點沒有所有的背景資料,是不是真正相關:http://stackoverflow.com/questions/17650616/set-body-to-height-of-contianing-fixed-元素 – Himmators

回答

2

如果您將其設置爲position: absolute;,並且它沒有非靜態定位父母,應該修復它。正如你所指出的那樣,固定的元素不會爲文檔貢獻高度,而絕對的元素則可以。

身高設置到包裝高度會給你滾動與固定定位的行爲,如果這就是你需要

http://jsfiddle.net/ULLBw/3/

<div class='wrapper'>click me</div> 

JS

$('.wrapper').on('click', function() { 
    $(this).toggleClass('fixed'); 
}); 

$('body').height($('.wrapper').height()); 

CSS

.wrapper { 
    height: 2000px; 
    width: 100%; 
    position: absolute; 
    top: 0 

    background-color: #e0e0e0; 
} 

.wrapper.fixed { 
    position: fixed; 
} 
+0

嗯......我想才達到固定位置行爲的CSS 。通過這種方法,當我滾動頁面的元素是不固定的... – Himmators

+0

我想我不明白的要求。如果包裝具有固定的行爲,但內容比屏幕更長,則永遠不會看到其餘的內容,對吧?或者你想要一切都留在原地,直到你到達一定的距離? –

+0

是的,這是確切的!當我開始滾動時,屏幕上正在發生其他一些事情,但過了一段時間,我希望它回退到默認行爲:) – Himmators