【问题标题】:How to move 1 div faster/over a div when the page is scrolled滚动页面时如何更快/超过 div 移动 1 个 div
【发布时间】:2013-02-11 01:42:16
【问题描述】:

我看到了这个效果here。 当页面滚动时,页面的主要内容部分会移动到 div 上方。

我尝试使用视差效果重新创建此效果,但徒劳无功。问题是使用视差,我只能在同一个 div 中更改 2 个对象的速度。除此之外,我将不得不放一些不必要的在整个页面上添加标签以使脚本正常工作。

有没有更简单(或有效)的方法来实现这个效果?非常感谢

【问题讨论】:

  • 你试过的代码!!!
  • @Murali ~ 哇。冷静。

标签: javascript jquery html css scroll


【解决方案1】:

You can do this with CSS.

#head, #subHead{
    position: fixed;           
    height: 80px;    
    width: 100%;
    display: block;
    left: 0;
    top: 0;
    z-index: 10;         /* on top of all */
}

#subHead{
    z-index: 4;          /* below all */
    top: 80px;           /* height of the top div */
}

#content{
    position: relative;
    z-index: 6;          /* below the top div, but above the one below it */
    margin-top: 160px;   /* the height of the two divs above combined */
}

并且让 subHead 滚动更慢:

window.onscroll = function(ev){
  var subHead = document.getElementById('subHead'),
      topHeight = document.getElementById('head').offsetHeight;

  subHead.style.top = (topHeight - document.body.scrollTop / 4) + 'px';
};    

jQuery:

$(window).on('scroll', function(){  
  $('#subHead').css('top', ($('#head').height() - $('body').scrollTop() / 4));
}); 

【讨论】:

  • 非常感谢,特别是后面的部分。你为什么用“i”“can”“has”...我知道网站管理员:)
  • $.on 在 jQuery 1.6 中不可用。包含更新的 jQuery 版本,或 use $.bind instead
【解决方案2】:

至少似乎确实存在一些视差。我没有仔细查看标记,但需要注意的一点是图形区域和内容区域(以及广告区域)是兄弟<div>s。

只是顶部,带有一些 CSS positioning 和 z-indexing,将内容 <div> 呈现在图形 <div> 上方会有点简单。似乎只有图形<div> 是通过视差滚动来控制的。如果这有意义的话。

【讨论】:

    【解决方案3】:

    您可以为您的第一个 div 附加 onscroll 事件并在您的 JS 中设置第二个 div 的滚动位置。

    <div id="div1" onscroll="OnScrollDiv()">
        <div id="div2"></div>
    </div>
    

    javascript:

    function OnScrollDiv () {
        var div1 = document.getElementById("div1");
        var div2 = document.getElementById("div2");
        div2.scrollTop = div1.scrollTop * 2;
    }
    

    更多信息在这里: http://help.dottoro.com/ljurkcpe.php http://help.dottoro.com/ljnvjiow.php

    【讨论】:

    • 除了上述代码之外,我们还需要添加什么代码才能使其正常工作吗?jsfiddle.net/ETuTg 随时告诉我,我对代码中的任何错误都很愚蠢
    • 在 jsfiddle 上对我不起作用...我在本地电脑上创建了一个示例 html 页面,这是它的内容:pastebin.com/9qSB5K0U 尝试在本地机器上运行它,检查是否有用。我添加警报只是为了检查滚动值。
    猜你喜欢
    • 2010-12-10
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    相关资源
    最近更新 更多