如果滚动到屏幕顶部,如何将div粘贴到屏幕顶部?

eva*_*anr 293 javascript css jquery scroll positioning

我想创建一个div,它位于一个内容块下面,但是一旦页面滚动到足以接触其顶部边界,就会固定到位并与页面一起滚动.我知道我至少看过一个这样的在线例子,但我不记得它对我的生活.

有什么想法吗?

CMS*_*CMS 244

你可以使用简单的css,将你的元素定位为固定的:

.fixedElement {
    background-color: #c0c0c0;
    position:fixed;
    top:0;
    width:100%;
    z-index:100;
}
Run Code Online (Sandbox Code Playgroud)

编辑:您应该具有位置绝对的元素,一旦滚动偏移到达元素,它应该被更改为固定,并且顶部位置应该设置为零.

您可以使用scrollTop函数检测文档的顶部滚动偏移:

$(window).scroll(function(e){ 
  var $el = $('.fixedElement'); 
  var isPositionFixed = ($el.css('position') == 'fixed');
  if ($(this).scrollTop() > 200 && !isPositionFixed){ 
    $el.css({'position': 'fixed', 'top': '0px'}); 
  }
  if ($(this).scrollTop() < 200 && isPositionFixed){
    $el.css({'position': 'static', 'top': '0px'}); 
  } 
});
Run Code Online (Sandbox Code Playgroud)

当滚动偏移达到200时,元素将粘贴到浏览器窗口的顶部,因为它被放置为固定的.

  • 这几乎是什么时候,但是当窗口滚动回到顶部时,我确实必须删除固定定位.`if($(this).scrollTop()<200 && $ el.css('position')=='fixed'){$('.fixedElement').css({'position':'static','顶部':'0px'}); }` (9认同)
  • 这并没有取得我想要的东西.我希望元素从页面顶部200px开始(为其他内容留出空间),然后一旦用户向下滚动就固定在顶部. (4认同)
  • 你的编辑确实填满了问题的需要,但当页面再次滚动回到顶部时你仍然有问题.你可以在到达元素之后将scrollTop存储在某个地方,当页面再次到达该位置时(向上滚动时)将css更改回默认值...可能最好使用.toggleClass执行此操作然后... (3认同)

Jos*_*Lee 242

您已经在Google代码的问题页面和(仅在最近)Stack Overflow的编辑页面上看到了此示例.

当您向后滚动时,CMS的答案不会还原定位.这是来自Stack Overflow的无耻窃取的代码:

function moveScroller() {
    var $anchor = $("#scroller-anchor");
    var $scroller = $('#scroller');

    var move = function() {
        var st = $(window).scrollTop();
        var ot = $anchor.offset().top;
        if(st > ot) {
            $scroller.css({
                position: "fixed",
                top: "0px"
            });
        } else {
            $scroller.css({
                position: "relative",
                top: ""
            });
        }
    };
    $(window).scroll(move);
    move();
}
Run Code Online (Sandbox Code Playgroud)
<div id="sidebar" style="width:270px;"> 
  <div id="scroller-anchor"></div> 
  <div id="scroller" style="margin-top:10px; width:270px"> 
    Scroller Scroller Scroller
  </div>
</div>

<script type="text/javascript"> 
  $(function() {
    moveScroller();
  });
</script> 
Run Code Online (Sandbox Code Playgroud)

还有一个简单的现场演示.

position: stickyChrome,Firefox和Safari支持新的无脚本替代方案.请参阅有关HTML5Rocks演示以及Mozilla文档的文章.

  • 出于某种原因,{scroll:false}给了我一些问题(jQuery 1.6.2).没有它似乎工作.来自链接演示的[Fork](http://jsfiddle.net/bv5y5/embedded/result/).知道它是否有用? (3认同)
  • 当我使用与demo(1.3.2)相同版本的jQuery时,这似乎工作得很好.在某些时候,`offset`必须已经停止接受一个对象作为输入http://api.jquery.com/offset/.@Eddie使用当前的jQuery,您的修改应该是安全的. (2认同)

Col*_*art 53

截至2017年1月和Chrome 56发布,大多数常用浏览器都支持 position: sticky CSS中属性.

#thing_to_stick {
  position: sticky;
  top: 0px;
}
Run Code Online (Sandbox Code Playgroud)

在Firefox和Chrome中为我做了诀窍.

在Safari中你仍然需要使用position: -webkit-sticky.

Polyfills可用于Internet Explorer和Edge; https://github.com/wilddeer/stickyfill似乎很好.

  • 目前常用的大多数浏览器都支持此功能.请参阅caniuse.com/#feat=css-sticky其次,我更喜欢一个解决方案,可以归结为2行代码到需要自定义Javascript的版本.而且它也是面向未来的.如果您担心浏览器兼容性,请使用polyfill. (5认同)
  • 没有比这更容易的了:) (2认同)
  • 我想在此评论中添加我们可以 z-index: 99999; ,因为如果不是当它到达顶部时,将首先呈现其他内容。但这应该是公认的解决方案。 (2认同)

Don*_* V. 33

我遇到了和你一样的问题,最后制作了一个jQuery插件来处理它.它实际上解决了人们在这里列出的所有问题,此外它还增加了一些可选功能.

选项

stickyPanelSettings = {
    // Use this to set the top margin of the detached panel.
    topPadding: 0,

    // This class is applied when the panel detaches.
    afterDetachCSSClass: "",

    // When set to true the space where the panel was is kept open.
    savePanelSpace: false,

    // Event fires when panel is detached
    // function(detachedPanel, panelSpacer){....}
    onDetached: null,

    // Event fires when panel is reattached
    // function(detachedPanel){....}
    onReAttached: null,

    // Set this using any valid jquery selector to 
    // set the parent of the sticky panel.
    // If set to null then the window object will be used.
    parentSelector: null
};
Run Code Online (Sandbox Code Playgroud)

https://github.com/donnyv/sticky-panel

演示: http ://htmlpreview.github.io/?https://github.com/donnyv/sticky-panel/blob/master/jquery.stickyPanel/Main.htm

  • 还添加了parentSelector选项以支持滚动div. (4认同)
  • @WillHancock我添加了iPad支持,修复了刷新bug并添加了onDetached和onReattached事件.新事件将使您在分离和重新连接后可以访问面板和spacerpanel. (2认同)

Jim*_*ica 24

以下是没有 jquery的方法(更新:请参阅其他答案,您现在只能使用CSS执行此操作)

var startProductBarPos=-1;
window.onscroll=function(){
  var bar = document.getElementById('nav');
  if(startProductBarPos<0)startProductBarPos=findPosY(bar);

  if(pageYOffset>startProductBarPos){
    bar.style.position='fixed';
    bar.style.top=0;
  }else{
    bar.style.position='relative';
  }

};

function findPosY(obj) {
  var curtop = 0;
  if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop;
      obj = obj.offsetParent;
    }
    curtop += obj.offsetTop;
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}
Run Code Online (Sandbox Code Playgroud)
* {margin:0;padding:0;}
.nav {
  border: 1px red dashed;
  background: #00ffff;
  text-align:center;
  padding: 21px 0;

  margin: 0 auto;
  z-index:10; 
  width:100%;
  left:0;
  right:0;
}

.header {
  text-align:center;
  padding: 65px 0;
  border: 1px red dashed;
}

.content {
  padding: 500px 0;
  text-align:center;
  border: 1px red dashed;
}
.footer {
  padding: 100px 0;
  text-align:center;
  background: #777;
  border: 1px red dashed;
}
Run Code Online (Sandbox Code Playgroud)
<header class="header">This is a Header</header>
<div id="nav" class="nav">Main Navigation</div>
<div class="content">Hello World!</div>
<footer class="footer">This is a Footer</footer>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这些天很难找到本机JS解决方案.这非常有效. (4认同)

Mar*_*avi 21

最简单的解决方案(没有js): demo

.container {
  position: relative;
}
.sticky-div {
    position: sticky;
    top: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <h1>
    relative container & sticky div
  </h1>
  <div class="sticky-div"> this row is sticky</div>
  <div>
    content
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)


Joh*_*hnB 9

这就是我用jquery做的.这是从堆栈溢出的各种答案拼凑而成的.该解决方案缓存选择器以获得更快的性能,并且当粘性div变粘时也解决了"跳跃"问题.

在jsfiddle上查看:http://jsfiddle.net/HQS8s/

CSS:

.stick {
    position: fixed;
    top: 0;
}
Run Code Online (Sandbox Code Playgroud)

JS:

$(document).ready(function() {
    // Cache selectors for faster performance.
    var $window = $(window),
        $mainMenuBar = $('#mainMenuBar'),
        $mainMenuBarAnchor = $('#mainMenuBarAnchor');

    // Run this on scroll events.
    $window.scroll(function() {
        var window_top = $window.scrollTop();
        var div_top = $mainMenuBarAnchor.offset().top;
        if (window_top > div_top) {
            // Make the div sticky.
            $mainMenuBar.addClass('stick');
            $mainMenuBarAnchor.height($mainMenuBar.height());
        }
        else {
            // Unstick the div.
            $mainMenuBar.removeClass('stick');
            $mainMenuBarAnchor.height(0);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)


kun*_*nde 6

这是另一种选择:

JAVASCRIPT

var initTopPosition= $('#myElementToStick').offset().top;   
$(window).scroll(function(){
    if($(window).scrollTop() > initTopPosition)
        $('#myElementToStick').css({'position':'fixed','top':'0px'});
    else
        $('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
});
Run Code Online (Sandbox Code Playgroud)

#myElementToStick应该从position:absoluteCSS属性开始.


Kal*_*ing 6

正如Josh LeeColin 't Hart所说,您可以选择只使用position: sticky; top: 0;应用到您想要滚动的 div ......

另外,您唯一需要做的就是将其复制到页面顶部或将其格式化以适合外部 CSS 表:

<style>
#sticky_div's_name_here { position: sticky; top: 0; }
</style>
Run Code Online (Sandbox Code Playgroud)

只需替换#sticky_div's_name_here为您的 div 的名称,即如果您的 div 是<div id="example">您将把#example { position: sticky; top: 0; }.