简体   繁体   English

在某一点停止固定位置滚动?

[英]Stopping fixed position scrolling at a certain point?

I have an element that is position:fixed and so scrolls with the page how i want it to however. 我有一个位置固定的元素,因此滚动页面我想要的方式。 when the user scrolls up I want the element to stop scrolling at a certain point, say when it is 250px from the top of the page, is this possible? 当用户向上滚动时,我希望元素在某一点停止滚动,比如当它距离页面顶部250px时,这可能吗? Any help or advice would be helpful thanks! 任何帮助或建议都会有所帮助,谢谢!

I had a feeling that I would need to use jquery to do so. 我有一种感觉,我需要使用jquery这样做。 I tried getting the scrolling or location of the where the user is but got really confused, is there any jquery solutions? 我尝试获取用户所在位置的滚动或位置,但真的很困惑,是否有任何jquery解决方案?

Do you mean sort of like this? 你的意思是这样吗?

http://jsfiddle.net/b43hj/ 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> 

Here's a quick jQuery plugin I just wrote that can do what you require: 这是我刚刚编写的一个快速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 → 见工作示例→

Here is a complete jquery plugin that solves this problem: 这是一个完整的jquery插件,可以解决这个问题:

https://github.com/bigspotteddog/ScrollToFixed https://github.com/bigspotteddog/ScrollToFixed

The description of this plugin is as follows: 这个插件的描述如下:

This plugin is used to fix elements to the top of the page, if the element would have scrolled out of view, vertically; 此插件用于将元素固定到页面顶部,如果元素将垂直滚出视图; however, it does allow the element to continue to move left or right with the horizontal scroll. 但是,它确实允许元素继续向左或向右移动水平滚动。

Given an option marginTop, the element will stop moving vertically upward once the vertical scroll has reached the target position; 给定选项marginTop,一旦垂直滚动到达目标位置,元素将停止垂直向上移动; but, the element will still move horizontally as the page is scrolled left or right. 但是,当页面向左或向右滚动时,元素仍将水平移动。 Once the page has been scrolled back down past the target position, the element will be restored to its original position on the page. 页面向下滚动到目标位置后,元素将恢复到页面上的原始位置。

This plugin has been tested in Firefox 3/4, Google Chrome 10/11, Safari 5, and Internet Explorer 8/9. 此插件已在Firefox 3/4,Google Chrome 10/11,Safari 5和Internet Explorer 8/9中进行了测试。

Usage for your particular case: 用于您的特定情况:

<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 });
});

You can do what James Montagne did with his code in his answer, but that will make it flicker in Chrome (tested in V19). 你可以在他的回答中做James Montagne用他的代码做的事情,但这会使它在Chrome中闪烁(在V19中测试)。

You can fix that if you put "margin-top" instead of "top". 你可以解决这个问题,如果你把“margin-top”而不是“top”。 Don't really know why it works with margin tho. 真的不知道为什么它适用于margin。

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

http://jsbin.com/idacel http://jsbin.com/idacel

A possible CSS ONLY solution can be achived with position: sticky; 一个可能的CSS ONLY解决方案可以获得position: sticky;

The browser support is actually really good: https://caniuse.com/#search=position%3A%20sticky 浏览器支持实际上非常好: https//caniuse.com/#search=position%3A%20sticky

here is an example: https://jsfiddle.net/0vcoa43L/7/ 这是一个例子: https//jsfiddle.net/0vcoa43L/7/

my solution 我的解决方案

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

In a project, I actually have some heading fixed to the bottom of the screen on page load (it's a drawing app so the heading is at the bottom to give maximum space to the canvas element on wide viewport). 在一个项目中,我实际上在页面加载时将一些标题固定到屏幕的底部(它是一个绘图应用程序,因此标题位于底部,以便为宽视口上的canvas元素提供最大空间)。

I needed the heading to become 'absolute' when it reaches the footer on scroll, since I don't want the heading over the footer (heading colour is same as footer background colour). 当滚动到达页脚时,我需要标题变为'绝对',因为我不希望标题超过页脚(标题颜色与页脚背景颜色相同)。

I took the oldest response on here (edited by Gearge Millo) and that code snippet worked for my use-case. 我在这里采用了最早的回复(由Gearge Millo编辑),并且该代码段适用于我的用例。 With some playing around I got this working. 随着一些游戏,我得到了这个工作。 Now the fixed heading sits beautifully above the footer once it reaches the footer. 现在,一旦到达页脚,固定标题就位于页脚上方。

Just thought I'd share my use-case and how it worked, and say thank you! 只是想我会分享我的用例以及它是如何工作的,并说声谢谢! The app: http://joefalconer.com/web_projects/drawingapp/index.html 该应用程序: 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);
    }

I wrote a blog post about this that featured this function: 我写了一篇关于此的博客文章 ,其中包含以下功能:

$.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();
  });
};

A Solution using Mootools Framework. 使用Mootools框架的解决方案。

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

  1. Get Position(x & y) of the element where you want to stop the scroll using $('myElement').getPosition().x 使用$('myElement')获取要停止滚动的元素的位置(x和y).getPosition()。x

    $('myElement').getPosition().y $( 'myElement')。为getPosition()。ÿ

  2. For a animation sort of scroll use : 对于动画类型的滚动使用:

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

  3. To just set scroll immediately use : 要立即设置滚动使用:

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

Hope this Helps !! 希望这可以帮助 !! :D :d

I liked this solution 我喜欢这个解决方案

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

my problem was that I had to deal with a position relative container in Adobe Muse. 我的问题是我不得不在Adobe Muse中处理位置相对容器。

My solution: 我的解决方案

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

Just improvised mVChr code 只是即兴的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);

I adapted @mVchr's answer and inverted it to use for sticky ad positioning: if you need it absolutely positioned (scrolling) until the header junk is off screen but then need it to stay fixied/visible on screen after that: 我调整了@ 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: CSS:

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

I loved @james answer but I was looking for its inverse ie stop fixed position right before footer, here is what I came up with 我喜欢@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));
    }

So now the fixed element would stop right before footer. 所以现在固定元素会在页脚之前停止。 and will not overlap with it. 并且不会与它重叠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM