【问题标题】:Stopping fixed position scrolling at a certain point?在某个点停止固定位置滚动?
【发布时间】:2011-08-19 15:46:40
【问题描述】:

我有一个 position:fixed 元素,因此可以随页面滚动,但我希望它如何。当用户向上滚动时,我希望元素在某个点停止滚动,比如距离页面顶部 250px 时,这可能吗?任何帮助或建议都会有所帮助,谢谢!

我有一种感觉,我需要使用 jquery 来做到这一点。我尝试获取用户所在位置的滚动或位置,但真的很困惑,有没有 jquery 解决方案?

【问题讨论】:

  • 据我所知,只有基于 javascript 的解决方案才能满足您的需求。没有纯 CSS 解决方案可以做到这一点。

标签: jquery css positioning


【解决方案1】:

你的意思是这样的吗?

http://jsfiddle.net/b43hj/

$(window).scroll(function(){
    $("#theFixed").css("top", Math.max(0, 250 - $(this).scrollTop()));
});

$(window).scroll(function(){
    $("#theFixed").css("top", Math.max(0, 100 - $(this).scrollTop()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="theFixed" style="position:fixed;top:100px;background-color:red">SOMETHING</div>

<!-- random filler to allow for scrolling -->
STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>

【讨论】:

  • 太好了,非常感谢!虽然我的任务是创建始终位于页脚上方的“到顶部”按钮,但我稍微修改了这段代码。在这里查看我的版本(js 咖啡):jsfiddle.net/9vnwx3fa/2
  • @James Montagne - 如果我想要固定元素粘性底部,那么反转此代码的解决方案是什么:0;滚动,然后在到达页面底部之前停止 250 像素?
  • @BoneStarr 这有点复杂。您需要将当前的 scrollTop 与页面的高度和视口进行比较。然后您只需使用上面相同的代码,除了 bottom 和这个计算值(偏移 250)在最大值中。
  • @JamesMontagne - 你有机会详细说明这个小提琴吗?真的很感激,因为我坚持这个。 jsfiddle.net/Hf5wH/137
  • @bonestarr 比这个复杂得多。您应该将其扩展为多行代码,否则很难理解。 jsfiddle.net/Hf5wH/139
【解决方案2】:

这是我刚刚编写的一个快速 jQuery 插件,可以满足您的需求:

$.fn.followTo = function (pos) {
    var $this = this,
        $window = $(window);

    $window.scroll(function (e) {
        if ($window.scrollTop() > pos) {
            $this.css({
                position: 'absolute',
                top: pos
            });
        } else {
            $this.css({
                position: 'fixed',
                top: 0
            });
        }
    });
};

$('#yourDiv').followTo(250);

See working example →

【讨论】:

  • 这看起来很有希望,是的,我想在某些点改变定位,我让你知道我的进展如何,谢谢!
  • 嗨,是的,非常感谢您,用了几周的时间就完全达到了我想要的效果,现在再次完美运行,再次感谢。
  • $('window') 不应该用引号引起来。不过谢谢你,这很有帮助。
【解决方案3】:

这里有一个完整的jquery插件可以解决这个问题:

https://github.com/bigspotteddog/ScrollToFixed

这个插件的描述如下:

此插件用于将元素固定到页面顶部,如果元素会垂直滚动到视图之外;但是,它确实允许元素随着水平滚动继续向左或向右移动。

给定一个选项marginTop,一旦垂直滚动到达目标位置,元素将停止垂直向上移动;但是,当页面向左或向右滚动时,元素仍会水平移动。一旦页面向下滚动超过目标位置,元素将恢复到页面上的原始位置。

此插件已在 Firefox 3/4、Google Chrome 10/11、Safari 5 和 Internet Explorer 8/9 中测试。

用于您的特定情况:

<script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery-scrolltofixed-min.js" type="text/javascript"></script>

$(document).ready(function() {
    $('#mydiv').scrollToFixed({ marginTop: 250 });
});

【讨论】:

  • 谢谢,是的,这看起来非常有用,我使用了以前的答案,因为这个项目是几个月前的,但是我肯定会在以后的项目中记住这一点,它看起来更容易,谢谢 :)跨度>
【解决方案4】:

一个可能的CSS ONLY解决方案可以通过position: sticky;实现

浏览器支持其实非常好: https://caniuse.com/#search=position%3A%20sticky

这是一个例子: https://jsfiddle.net/0vcoa43L/7/

【讨论】:

  • 很遗憾不适用于 IE11
  • 这是一个非常好的和简单的解决方案,我花了一点时间才理解它,但其中一个关键实际上是父元素需要一个高度。在我的情况下,应该是粘性的子元素是浮动的,所以父元素最初没有高度。 stackoverflow.com/a/4805371/368479 让我走上正轨,display: flex; 在父级上。
【解决方案5】:

您可以像 James Montagne 在他的回答中对他的代码所做的那样,但这会使它在 Chrome 中闪烁(在 V19 中测试)。

如果您使用“margin-top”而不是“top”,您可以解决此问题。真的不知道为什么它适用于边距。

$(window).scroll(function(){
    $("#theFixed").css("margin-top",Math.max(-250,0-$(this).scrollTop()));
});

http://jsbin.com/idacel

【讨论】:

  • 这对于文本下方的固定元素也很有效,我一直遇到小屏幕显示的严重问题,并且我的固定滚动元素在较小的区域(如 1024x768)上运行到浏览器顶部。这解决了这个问题。
【解决方案6】:

我的解决方案

$(window).scroll(function(){
        if($(this).scrollTop()>425) {
            $("#theRelative").css("margin-top",$(this).scrollTop()-425);
            }   else {
                $("#theRelative").css("margin-top",$(this).scrollTop()-0);
                }
            });
            });

【讨论】:

    【解决方案7】:

    在一个项目中,我实际上在页面加载时将一些标题固定在屏幕底部(它是一个绘图应用程序,因此标题位于底部,以便为宽视口上的画布元素提供最大空间)。

    我需要标题在滚动到页脚时变为“绝对”,因为我不希望页脚上方的标题(标题颜色与页脚背景颜色相同)。

    我在这里接受了最古老的响应(由 Gearge Millo 编辑),该代码 sn-p 适用于我的用例。随着一些玩耍,我得到了这个工作。现在,一旦固定标题到达页脚,它就会漂亮地位于页脚上方。

    只是想我会分享我的用例及其工作原理,并说声谢谢! 应用程序:http://joefalconer.com/web_projects/drawingapp/index.html

        /* CSS */
        @media screen and (min-width: 1100px) {
            #heading {
                height: 80px;
                width: 100%;
                position: absolute;  /* heading is 'absolute' on page load. DOESN'T WORK if I have this on 'fixed' */
                bottom: 0;
            }
        }
    
        // jQuery
        // Stop the fixed heading from scrolling over the footer
        $.fn.followTo = function (pos) {
          var $this = this,
          $window = $(window);
    
          $window.scroll(function (e) {
            if ($window.scrollTop() > pos) {
              $this.css( { position: 'absolute', bottom: '-180px' } );
            } else {
              $this.css( { position: 'fixed', bottom: '0' } );
            }
          });
        };
        // This behaviour is only needed for wide view ports
        if ( $('#heading').css("position") === "absolute" ) {
          $('#heading').followTo(180);
        }
    

    【讨论】:

      【解决方案8】:

      I wrote a blog post about this 具有此功能:

      $.fn.myFixture = function (settings) {
        return this.each(function () {
      
          // default css declaration 
          var elem = $(this).css('position', 'fixed');
      
          var setPosition = function () {         
            var top = 0;
            // get no of pixels hidden above the the window     
            var scrollTop = $(window).scrollTop();    
            // get elements distance from top of window
            var topBuffer = ((settings.topBoundary || 0) - scrollTop);
            // update position if required
            if (topBuffer >= 0) { top += topBuffer }
            elem.css('top', top);      
          };
      
          $(window).bind('scroll', setPosition);
          setPosition();
        });
      };
      

      【讨论】:

        【解决方案9】:

        使用 Mootools 框架的解决方案。

        http://mootools.net/docs/more/Fx/Fx.Scroll

        1. 获取要停止滚动的元素的 Position(x & y) 使用 $('myElement').getPosition().x

          $('myElement').getPosition().y

        2. 对于动画类型的滚动使用:

          new Fx.Scroll('scrollDivId', {offset: {x: 24,y: 432} }).toTop();

        3. 要立即设置滚动,请使用:

          new Fx.Scroll(myElement).set(x,y);

        希望这会有所帮助! :D

        【讨论】:

          【解决方案10】:

          我喜欢这个解决方案

          $(window).scroll(function(){
              $("#theFixed").css("margin-top",Math.max(-250,0-$(this).scrollTop()));
          });
          

          我的问题是我必须在 Adob​​e Muse 中处理相对位置的容器。

          我的解决方案:

          $(window).scroll(function(){
              if($(this).scrollTop()>425) {
                   $("#theRelative").css("margin-top",$(this).scrollTop()-425);
              }
          });
          

          【讨论】:

            【解决方案11】:

            即兴创作的 mVChr 代码

            $(".sidebar").css('position', 'fixed')
            
                var windw = this;
            
                $.fn.followTo = function(pos) {
                    var $this = this,
                            $window = $(windw);
            
                    $window.scroll(function(e) {
                        if ($window.scrollTop() > pos) {
                            topPos = pos + $($this).height();
                            $this.css({
                                position: 'absolute',
                                top: topPos
                            });
                        } else {
                            $this.css({
                                position: 'fixed',
                                top: 250 //set your value
                            });
                        }
                    });
                };
            
                var height = $("body").height() - $("#footer").height() ;
                $('.sidebar').followTo(height);
                $('.sidebar').scrollTo($('html').offset().top);
            

            【讨论】:

            • 将$(this) 和$(window) 存储在变量中的原因是你只需要做$this.height() 等等。如果插件存储原始顶部值并在设置固定宽度时恢复到它,而不是设置顶部位置会更好吗?另外,Just improvised mVChr code 是什么意思?
            【解决方案12】:

            我调整了@mVchr 的答案并将其反转以用于粘性广告定位:如果您需要它绝对定位(滚动)直到标题垃圾不在屏幕上,但之后需要它在屏幕上保持固定/可见:

            $.fn.followTo = function (pos) {
                var stickyAd = $(this),
                theWindow = $(window);
                $(window).scroll(function (e) {
                  if ($(window).scrollTop() > pos) {
                    stickyAd.css({'position': 'fixed','top': '0'});
                  } else {
                    stickyAd.css({'position': 'absolute','top': pos});
                  }
                });
              };
              $('#sticky-ad').followTo(740);
            

            CSS:

            #sticky-ad {
                float: left;
                display: block;
                position: absolute;
                top: 740px;
                left: -664px;
                margin-left: 50%;
                z-index: 9999;
            }
            

            【讨论】:

              【解决方案13】:

              我喜欢@james 的答案,但我一直在寻找它的反面,即在页脚之前停止固定位置,这就是我想出的

              var $fixed_element = $(".some_element")
              if($fixed_element.length){
                      var $offset = $(".footer").position().top,
                          $wh = $(window).innerHeight(),
                          $diff = $offset - $wh,
                          $scrolled = $(window).scrollTop();
                      $fixed_element.css("bottom", Math.max(0, $scrolled-$diff));
                  }
              

              所以现在固定元素会在页脚之前停止。并且不会与它重叠。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2018-01-01
                • 1970-01-01
                • 2023-03-28
                • 1970-01-01
                • 2021-04-24
                • 1970-01-01
                • 1970-01-01
                • 2016-07-03
                相关资源
                最近更新 更多