¿Cómo hacer que div siga desplazándose suavemente con jQuery?

En mi contenedor hay secciones / cuadros, pero el último de estos cuadros debe seguir desplazándose cuando ninguno de los otros cuadros está visible .

Entonces, cuando el usuario se desplaza hacia abajo, ve una barra lateral normal, pero cuando el usuario ha bajado lo suficiente, la barra lateral termina pero el último cuadro comienza a seguir en la parte superior de la pantalla. He visto esto mucho en diferentes tipos de sitios.

Mi código en este momento:

$(window).scroll(function(){ $.each($('.follow-scroll'),function(){ var eloffset = $(this).offset(); var windowpos = $(window).scrollTop(); if(windowpos<eloffset.top) { var finaldestination = 0; } else { var finaldestination = windowpos; } $(this).stop().animate({'top':finaldestination},200); }); }); 

Como esta pregunta tiene muchas vistas y el tutorial vinculado a la respuesta más votada parece estar fuera de línea, me tomé el tiempo para limpiar este script.

Véalo en vivo aquí: JSFiddle

JavaScript:

 (function($) { var element = $('.follow-scroll'), originalY = element.offset().top; // Space between element and top of screen (when scrolling) var topMargin = 20; // Should probably be set in CSS; but here just for emphasis element.css('position', 'relative'); $(window).on('scroll', function(event) { var scrollTop = $(window).scrollTop(); element.stop(false, false).animate({ top: scrollTop < originalY ? 0 : scrollTop - originalY + topMargin }, 300); }); })(jQuery); 

Hay un fantástico tutorial de jQuery para esto en https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/ .

Se replica el tipo de desplazamiento de la barra lateral del carrito de compras de Apple.com. La consulta de Google que podría haberle sido útil es “barra lateral flotante fija”.

La solución puede reducirse a esto, en mi humilde opinión:

 var el=$('#follow-scroll'); var elpos=el.offset().top; $(window).scroll(function () { var y=$(this).scrollTop(); if(y 

He cambiado la asignación de el porque, una vez más en mi humilde opinión, encontrar un solo elemento por clase no es un gran hábito para entrar. Si solo quieres un elemento, encuéntralo por id. Si desea iterar sobre una colección de elementos, búsquelos por clase.

Estoy usando this para mantener mi código pequeño pero, con suerte, ¡legible!

tenga en cuenta que mi respuesta aquí se refiere a la respuesta aceptada en ese momento (sigue siendo la respuesta aceptada en este momento, pero ha sido editada y, por lo tanto, mi respuesta ya no se reduce a lo que ve en la respuesta de @Martti Lane al respecto página, mi respuesta "reduce" su respuesta original aceptada; puede echar un vistazo al historial de edición de la respuesta de @Martti si está interesado en lo que "reduje").

Esto funcionó para mí como un encanto.

JavaScript:

 $(function() { //doc ready if (!($.browser == "msie" && $.browser.version < 7)) { var target = "#floating", top = $(target).offset().top - parseFloat($(target).css("margin-top").replace(/auto/, 0)); $(window).scroll(function(event) { if (top <= $(this).scrollTop()) { $(target).addClass("fixed"); } else { $(target).removeClass("fixed"); } }); } }); 

CSS:

 #floating.fixed{ position:fixed; top:0; } 

Fuente: http://jqueryfordesigners.com/fixed-floating-elements/

Este es mi código final … (basado en correcciones anteriores, muchas gracias por la cabecera, ahorré mucho tiempo de experimentación). Lo que me molestó fue desplazarse hacia arriba, así como desplazarse hacia abajo … 🙂

siempre me hace preguntarme cómo puede ser elegante JQuery !!!

 $(document).ready(function(){ //run once var el=$('#scrolldiv'); var originalelpos=el.offset().top; // take it where it originally is on the page //run on scroll $(window).scroll(function(){ var el = $('#scrolldiv'); // important! (local) var elpos = el.offset().top; // take current situation var windowpos = $(window).scrollTop(); var finaldestination = windowpos+originalelpos; el.stop().animate({'top':finaldestination},500); }); }); 

Aquí está la solución mía (espero que también sea plug-n-play ):

  1. Copie la parte del código JS
  2. Agregue la clase ‘slide-along-scroll’ al elemento que desee
  3. Haga correcciones de píxeles perfectos en código JS
  4. ¡Esperamos que lo disfrutes!
 // SlideAlongScroll var SlideAlongScroll = function(el) { var _this = this; this.el = el; // elements original position this.elpos_original = el.parent().offset().top; // scroller timeout this.scroller_timeout; // scroller calculate function this.scroll = function() { // 20px gap for beauty var windowpos = $(window).scrollTop() + 20; // targeted destination var finaldestination = windowpos - this.elpos_original; // define stopper object and correction amount var stopper = ($('.footer').offset().top); // $(window).height() if you dont need it var stophere = stopper - el.outerHeight() - this.elpos_original - 20; // decide what to do var realdestination = 0; if(windowpos > this.elpos_original) { if(finaldestination >= stophere) { realdestination = stophere; } else { realdestination = finaldestination; } } el.css({'top': realdestination }); }; // scroll listener $(window).on('scroll', function() { // debounce it clearTimeout(_this.scroller_timeout); // set scroll calculation timeout _this.scroller_timeout = setTimeout(function() { _this.scroll(); }, 300); }); // initial position (in case page is pre-scrolled by browser after load) this.scroll(); }; // init action, little timeout for smoothness $(document).ready(function() { $('.slide-along-scroll').each(function(i, el) { setTimeout(function(el) { new SlideAlongScroll(el); }, 300, $(el)); }); }); 
 /* part you need */ .slide-along-scroll { padding: 20px; background-color: #CCCCCC; transition: top 300ms ease-out; position: relative; } /* just demo */ div { box-sizing: border-box; } .side-column { float: left; width: 20%; } .main-column { padding: 20px; float: right; width: 75%; min-height: 1200px; background-color: #EEEEEE; } .body { padding: 20px 0; } .body:after { content: ' '; clear: both; display: table; } .header { padding: 20px; text-align: center; border-bottom: 2px solid #CCCCCC; } .footer { padding: 20px; border-top: 2px solid #CCCCCC; min-height: 300px; } 
  

Your super-duper website

Side menu content
  • Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  • Aliquam tincidunt mauris eu risus.
  • Vestibulum auctor dapibus neque.
Main content area (1200px)

Ese código no funciona muy bien lo arreglé un poco

 var el = $('.caja-pago'); var elpos_original = el.offset().top; $(window).scroll(function(){ var elpos = el.offset().top; var windowpos = $(window).scrollTop(); var finaldestination = windowpos; if(windowpos 

Necesitaba que el div se detuviera cuando alcanzaba cierto objeto, así que lo hice así:

 var el = $('#followdeal'); var elpos_original = el.offset().top; $(window).scroll(function(){ var elpos = el.offset().top; var windowpos = $(window).scrollTop(); var finaldestination = windowpos; var stophere = ( $('#filtering').offset().top ) - 170; if(windowpos=stophere) { finaldestination = elpos_original; el.stop().animate({'top':10}); } else { el.stop().animate({'top':finaldestination-elpos_original+10},500); } }); 

Este es el mismo en Facebook:

  
 body{ margin:0; padding:0; height:100%; } #demo{ position:fixed; height:100vh; overflow:hidden; width:40%; } #content{ position:relative; float:right; width:60%; color:red; } 
   
  • "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

  • "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

  • "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

  • "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

  • "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

  • "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

  • "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

  • "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

  • "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

  • "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

  • "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

  • "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

  • "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

  • "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

  • "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

Escribí una respuesta relativamente simple para esto.

Tengo una tabla que usa uno de los complementos del “encabezado de la tabla adhesiva” para pegar justo debajo de un div en particular en mi página, pero el menú a la izquierda de la tabla no se pega (ya que no es parte de la tabla).

Para mis propósitos, sabía que el div que necesitaba “adherencia” siempre iba a comenzar a 385 píxeles debajo de la parte superior de la ventana, así que creé un div vacío justo encima de eso:

 

Luego corrió esto:

 $(window).scroll(function(){ if ( $(window).scrollTop() > 385 ) { extraPadding = $(window).scrollTop() - 385; $('#stopMenu').css( "padding-top", extraPadding ); } else { $('#stopMenu').css( "padding-top", "0" ); } }); 

A medida que el usuario se desplaza, agrega el valor de $(window).scrollTop() al entero 385 , luego agrega ese valor al stopMenu div que está por encima de lo que quiero mantener enfocado.

En caso de que el usuario se desplace por completo hacia atrás, simplemente configuro el relleno extra en 0.

Esto no requiere que el usuario haga nada en particular en CSS, pero es un buen efecto hacer un pequeño retraso, así que puse la class="stopMenu" también:

 .stopMenu { .transition: all 0.1s; }