2013-07-15 156 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