向下滚动时标题会发生变化(jQuery)

TechCrunch最近重新设计了他们的网站,他们有一个甜蜜的标题,当你向下滚动时,它会缩小为更精简的品牌版本。

你可以在这里看到我的意思: http : //techcrunch.com/

我将如何创建这样的东西? 是否有任何地方的教程,如果没有,你可以帮助我一些关于从哪里开始的提示吗? 🙂

这不是太难,它只是一个简单的.scroll()事件。 由于面板的定位方式,我似乎无法在小提琴中进行 检查! 。 但基本上你所拥有的是顶部的divposition: absolute所以它总是在顶部,然后使用.scroll()

 $("body").scroll( function() { var top = $(this).scrollTop(); // if statement to do changes }); 

scrollTop()方法用于确定body滚动了多少。

根据您想要更改标题div的位置,您可以使用if语句执行许多操作。 在您提供的示例的情况下,它将是类似的

 if ( top > 147 ) // add the TechCrunch div inside the header else // hide the TechCrunch div so that space is transparent and you can see the banner 

编辑

好极了! 我能够用这个小提琴演示这个例子! 🙂

祝好运!

老问题,但我最近遇到了这个问题,这里接受的解决方案无法正常工作,因为我的div的高度没有固定,所以简而言之就是我遇到的解决方案。

JSfiddle: http //jsfiddle.net/Lighty_46/27f4k/12/

 $(document).ready(function () { var bluebutton = $('#blue_link').offset().top - parseFloat($('#blue_link').css('marginBottom').replace(/auto/, 0)); var bluebuttonbottom = $('#blue_block_bottom').offset().top - $('#main_nav').height() - parseFloat($('#blue_link').css('marginBottom').replace(/auto/, 0)); $(window).scroll(function (event) { // what the y position of the scroll is var y = $(this).scrollTop(); // whether that's below the top of the div if (y >= bluebutton) { // if so, ad the fixed class $('.home_nav').addClass('blue_selected'); } // whether you have passed the bottom of the div if (y >= bluebuttonbottom) { // if so remove the selected class $('.home_nav').removeClass('blue_selected'); } else { // otherwise remove it $('.home_nav').removeClass('blue_selected'); } }); }); 

基本上,

  • $(’#blue_link’)是我想要触发类更改的顶级div
  • $(’#blue_block_bottom’)是我想要触发类删除的div
  • $(’#main_nav’)是我的固定标题

所以当我的标题的底部到达div的顶部时,类“blue_selected”应用于“.home_nav”…..然后如果div的底部通过标题的底部,则“blue_selected”类是从“.home_nav”中删除。

您需要为每个按钮及其各自的div重复此操作

我已经在Chrome,Firefox和IE 10到8中进行了测试(在8中工作,但小提琴略有突破)。

希望这会有所帮助,它可能不是最诚实的方式,它可能在某处有一些错误,但它是我工作的唯一一个。

看看这个浮动分区

您正在寻找的是您需要将Div定义为浮动Div,然后每当您滚动时它始终保留在页面上。 在Techcrunch中,他们的头部位于中心顶部,所以它始终保持在那里

这是一个想法

  • 绑定到document.body.onscroll事件
  • onscroll检查滚动位置。 如果不在顶部,请替换条形图像
  • 如果它在顶部,则显示另一个图像
 $(window).on("scroll", function () { if ($(this).scrollTop() > 100) { $("#header").addClass("not-transparent"); } else { $("#header").removeClass("not-transparent"); } }); 

虽然之前的答案似乎是一个完美的解决方案,但似乎TechCrunch使用z-index和固定定位来实现这种滚动效果。

Desmond在Imageshack上

从上图中可以看出,大小标题都在屏幕上,如果不调整jQuery滚动事件就不会发生这种情况。

使用下面的代码作为我的工作