Detener el desplazamiento de posición fija en un punto determinado?


Tengo un elemento que es position:fixed y por lo tanto se desplaza con la página como quiero que sin embargo. cuando el usuario se desplaza hacia arriba quiero que el elemento deje de desplazarse en un cierto punto, digamos cuando es 250px desde la parte superior de la página, ¿es esto posible? Cualquier ayuda o consejo sería útil, gracias!

Tuve la sensación de que necesitaría usar jquery para hacerlo. Traté de obtener el desplazamiento o la ubicación de la donde está el usuario, pero me confundí mucho, ¿hay alguna solución de jquery?

Author: Louise McComiskey, 2011-05-05

13 answers

Aquí hay un plugin jQuery rápido que acabo de escribir que puede hacer lo que necesita:

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

Ver ejemplo de trabajo →

 113
Author: mVChr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-20 11:24:18

¿Te refieres a algo así?

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>
 126
Author: James Montagne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-17 14:57:44

Aquí hay un plugin jquery completo que resuelve este problema:

Https://github.com/bigspotteddog/ScrollToFixed

La descripción de este plugin es la siguiente:

Este complemento se usa para fijar elementos en la parte superior de la página, si el elemento se hubiera desplazado fuera de la vista, verticalmente; sin embargo, permite que el elemento continúe moviéndose hacia la izquierda o hacia la derecha con el desplazamiento horizontal.

Dada una opción marginTop, el elemento dejará de moverse verticalmente hacia arriba una vez que el desplazamiento vertical ha alcanzado la posición de destino; pero, el elemento seguirá moviéndose horizontalmente a medida que la página se desplaza hacia la izquierda o hacia la derecha. Una vez que la página se haya desplazado hacia abajo más allá de la posición de destino, el elemento se restaurará a su posición original en la página.

Este plugin ha sido probado en Firefox 3/4, Google Chrome 10/11, Safari 5 e Internet Explorer 8/9.

Uso para su caso particular:

<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 });
});
 18
Author: bigspotteddog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-29 16:49:19

Puedes hacer lo que James Montagne hizo con su código en su respuesta, pero eso hará que parpadee en Chrome (probado en V19).

Puedes arreglar eso si pones "margin-top" en lugar de "top". Realmente no sé por qué funciona con margin tho.

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

Http://jsbin.com/idacel

 6
Author: Jure Ravlić,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-21 13:17:28

En un proyecto, en realidad tengo un encabezado fijo en la parte inferior de la pantalla al cargar la página (es una aplicación de dibujo, por lo que el encabezado está en la parte inferior para dar el máximo espacio al elemento canvas en la ventana panorámica).

Necesitaba que el encabezado se convirtiera en 'absoluto' cuando llegue al pie de página en scroll, ya que no quiero el encabezado sobre el pie de página (el color del encabezado es el mismo que el color de fondo del pie de página).

Tomé la respuesta más antigua aquí (editada por Gearge Millo) y ese fragmento de código funcionó para mi caso de uso. Con un poco de juego tengo esto funcionando. Ahora el encabezado fijo se encuentra bellamente por encima del pie de página una vez que llega al pie de página.

Solo pensé en compartir mi caso de uso y cómo funcionó, y decir gracias! La aplicación: 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);
    }
 3
Author: joseph falconer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-17 17:34:07

Escribí una entrada de blog sobre esto que presentaba esta función:

$.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();
  });
};
 2
Author: Nathan McGinness,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-07 17:42:45

Mi solución

$(window).scroll(function(){
        if($(this).scrollTop()>425) {
            $("#theRelative").css("margin-top",$(this).scrollTop()-425);
            }   else {
                $("#theRelative").css("margin-top",$(this).scrollTop()-0);
                }
            });
            });
 2
Author: user3288218,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-08 21:07:29

Una posible CSS SOLO solución se puede obtener con position: sticky;

El soporte del navegador es realmente muy bueno: https://caniuse.com/#search=position%3A%20sticky

Aquí hay un ejemplo: https://jsfiddle.net/0vcoa43L/7 /

 2
Author: JiiB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-24 15:08:38

Una Solución usando el Framework Mootools.

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

  1. Obtener la posición (x e y) del elemento donde desea detener el desplazamiento con $('myElement').getPosition().x

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

  2. Para un tipo de desplazamiento de animación use:

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

  3. Para configurar el desplazamiento inmediatamente use:

    Nuevo Fx.De desplazamiento(myElement).set (x, y);

Espero que esto ayude !! : D

 0
Author: Zohaib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-26 06:05:49

Me gustó esta solución

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

Mi problema era que tenía que lidiar con un contenedor relativo de posición en Adobe Muse.

Mi solución:

$(window).scroll(function(){
    if($(this).scrollTop()>425) {
         $("#theRelative").css("margin-top",$(this).scrollTop()-425);
    }
});
 0
Author: leu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-31 07:50:14

Solo improvisó el código 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);
 0
Author: Sreeraj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-22 08:22:47

Adapté la respuesta de @mVchr y la invertí para usarla para el posicionamiento de anuncios pegajosos: si la necesita absolutamente posicionada (desplazándose) hasta que la basura del encabezado esté fuera de la pantalla, pero luego la necesita para permanecer fija / visible en la pantalla después de eso:

$.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;
}
 0
Author: cbmtrx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-24 07:14:36

Me encantó la respuesta de @james, pero estaba buscando su inversa, es decir, detener la posición fija justo antes del pie de página, esto es lo que se me ocurrió

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

Así que ahora el elemento fijo se detendría justo antes del pie de página. y no se superpondrá con él.

 0
Author: mshahbazm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-21 03:04:01