【问题标题】:Scroll Fixed Div Upon Collision碰撞时滚动固定 div
【发布时间】:2013-03-22 14:26:40
【问题描述】:

我正在尝试创建一个页面,顶部有两个固定 div(div1 和 div2),一个 div(div3),页面内容在下方自然流动。当用户滚动,div3到达div1的底部时,我希望两个div融合在一起并正常滚动。这个website 具有我试图复制的确切行为。

我正在使用不同的 z-index 将 div1 和 div3 保持在 div2 之上,并在 div1 和 div3 触摸时检测到:

$(window).scroll(function(e) {
    var calc = $("#div3").offset().top - $("#div1").height();
    if ($(this).scrollTop() >= calc) 
    {
        //fuse
    }
    else
    {
        //unfuse
    }
});

但我不知道如何将 div3 和 div1 融合在一起。

谢谢:)

【问题讨论】:

  • 元素很可能没有“融合在一起”——但固定位置只是更改为绝对位置,以便以前固定的元素随着其余内容滚动……

标签: javascript jquery


【解决方案1】:

这是一种解决方案。它依赖于.content 内的.header.content-inner.header 显示为 position:fixed 直到达到滚动阈值,此时将一个类添加到 .content 并且 .header 切换回 position:static,因此它又回到了页面的常规流程中。

.content-inner 是必要的,因为当.header 回到静态定位时,我们需要减少margin-top 以腾出空间。

jsFiddle

HTML

<div class="banner"></div>
<div class="content">
    <div class="header"></div>
    <div class="content-inner">
        ...
    </div>
</div>

CSS

body,
html {
    margin:0;
    padding:0;
}

.banner {
    position:fixed;
    z-index:-1;
    left:0;
    right:0;
    top:100px;
    height:300px;
    background-color:#F00;
}

.content {
    margin-top:400px;
    background-color:#FFF;
    position:relative;
}
.content.fuse {
    margin-top:300px;
}

.content-inner {
    background-color:#FFF;    
}

.header {
    position:fixed;
    height:100px;
    background-color:#00F;
    left:0;
    top:0;
    right:0;
}

.content.fuse .header {
    position:static;
}

JS

$(window).scroll(function(e) {
    if ($(window).scrollTop() < 300)
        $('.content').removeClass('fuse');
    else
        $('.content').addClass('fuse');
});

【讨论】:

  • 谢谢,@Tyriar。我了解您的解决方案,但无法将其改装到我现有的代码中,最终以您建议的方式重新设计了页面。所以,它有效!但我很难把我的想法包裹在这个概念上。例如,这个 [page] (npr.org/blogs/health/2013/03/20/174872904/…) 很有趣,但我想不通。你知道我可以阅读什么好的资源来赶上吗?提前谢谢。
  • @bre 该页面可能使用了非常相似的东西,只是处理$(window).scroll() 并在元素达到某个阈值时更改元素的样式。
猜你喜欢
  • 2020-04-22
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
相关资源
最近更新 更多