【问题标题】:"collapsing" position: fixed element using jquery“折叠”位置:使用 jquery 固定元素
【发布时间】:2011-03-09 12:12:01
【问题描述】:

我正在尝试实现徽标在this page 中的效果,它固定在页面顶部,但向下滚动时,只有一部分仍然可见,而不是整个元素。

我发现很多 jquery 插件可以将元素的顶部保持在页面顶部,但没有一个可以让我自定义元素的高度。我的 javascript 无法从头开始编写代码。有人对可能有用的插件有任何建议吗?

【问题讨论】:

    标签: javascript jquery jquery-plugins position fixed


    【解决方案1】:

    您不需要为此使用插件。 CSS 可以保持徽标固定不变,您可以在用户开始滚动页面后使用 JavaScript 更改元素的显示。

    假设您的徽标具有徽标 ID,则 CSS 将是:

    #logo {
      top: 0;
      position: fixed;
    }
    

    由于您使用的是 jQuery,因此您可以执行以下操作:

    $(function() {
    
      // gets a reference to the document based on which browser is being used
      var oDoc = $.browser.msie === true ? window : document;
    
      // event handler for when the user scrolls
      $(oDoc).scroll(function() {
    
        // if the user is at the top, display the whole image
        if($(this).scrollTop() === 0) {
          $('#logo').css('margin-top', 0);
    
        // otherwise, pull the image up a single em (200 is arbitrary)
        } else if($(this).scrollTop() > 200) {
          $('#logo').css('margin-top', '-1em');
        }
    
      });
    
    });
    

    【讨论】:

    • 效果很好,谢谢!比我想象的要容易得多。
    猜你喜欢
    • 2018-08-25
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多