如何让div跟随jQuery平滑滚动?

在我的容器中有部分/盒子,但是当其他盒子不可见时 ,这些盒子的最后一个应该跟着滚动。

所以,当用户向下滚动时,他会看到一个正常的侧边栏,但是当用户已经足够下滑时,边栏结束,但最后一个框开始跟随在屏幕的顶部。 我在不同types的网站上看到了很多。

我现在的代码是:

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

由于这个问题得到了很多的意见,并在最投票答案链接的教程似乎脱机,我花了时间来清理这个脚本。

在这里看到它: 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); 

有一个奇妙的jQuery教程在https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/

它复制Apple.com购物车types的侧边栏滚动。 可能为您提供良好服务的Google查询是“固定浮动边栏”。

解决办法可以归结为这个,在我的愚见:

 var el=$('#follow-scroll'); var elpos=el.offset().top; $(window).scroll(function () { var y=$(this).scrollTop(); if(y<elpos){el.stop().animate({'top':0},500);} else{el.stop().animate({'top':y-elpos},500);} }); 

我已经改变了el的任务,因为我认为,按照课堂上find一个单一的元素并不是一个很好的习惯。 如果你只想要一个元素通过idfind它。 如果你想遍历一个元素的集合,然后按类find它们。

我正在使用this来保持我的代码小,但希望,可读!

请注意 – 我的答案在这里指的是当时被接受的答案(它现在仍然是被接受的答案,但之后被编辑了,因此我的答案不再“归结”你在@Martti Lane的答案中看到的内容页面;我的回答“归结”他原来的,接受的答案;如果你对我所“冷落”的东西感兴趣,你可以看看@马蒂的答案的编辑历史。)

这对我来说就像一个魅力。

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

资料来源: http : //jqueryfordesigners.com/fixed-floating-elements/

这是我的最终代码….(基于以前的修复,谢谢大开眼界,节省了大量的时间试验)。 什么烦扰我滚动,以及滚动下来… 🙂

它总是让我想知道如何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); }); }); 

该代码不能很好地工作,我修复了一点点

 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<elpos_original) { finaldestination = elpos_original; el.stop().animate({'top':400},500); } else { el.stop().animate({'top':windowpos+10},500); } }); 

当它到达某个对象时,我需要div停止,所以我这样做了:

 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<elpos_original || windowpos>=stophere) { finaldestination = elpos_original; el.stop().animate({'top':10}); } else { el.stop().animate({'top':finaldestination-elpos_original+10},500); } }); 

这里是我的解决scheme(希望它也是即插即用的 ):

  1. 复制JS代码部分
  2. 将“slide-along-scroll”类添加到您想要的元素
  3. 在JS代码中进行像素完美修正
  4. 希望你会喜欢它!
 // 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; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div class="header"> <h1>Your super-duper website</h1> </div> <div class="body"> <div class="side-column"> <!-- part you need --> <div class="slide-along-scroll"> Side menu content <ul> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Aliquam tincidunt mauris eu risus.</li> <li>Vestibulum auctor dapibus neque.</li> </ul> </div> </div> <div class="main-column"> Main content area (1200px) </div> </div> <div class="footer"> Footer (slide along is limited by it) </div> </div> 

这个在Facebook上是一样的:

 <script> var valX = $(window).scrollTop(); function syncScroll(target){ var valY = $(window).scrollTop(); var difYX = valY - valX; var targetX = $(target).scrollTop(); if(valY > valX){ $(target).scrollTop(difYX); } if(difYX <= 0){ $(target).scrollTop(-20); } } $(window).scroll(function(){ syncScroll('#demo'); }) </script> 
 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; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="demo"> <ul> <li> <p>"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."</p> </li> <li> <p> "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?" </p> </li> <li> <p> "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?" </p> </li> <ul> </div> <div id="content"> <ul> <li> <p>"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."</p> </li> <li> <p> "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?" </p> </li> <li> <p> "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?" </p> </li> <li> <p>"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."</p> </li> <li> <p> "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?" </p> </li> <li> <p> "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?" </p> </li> <li> <p>"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."</p> </li> <li> <p> "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?" </p> </li> <li> <p> "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?" </p> </li> <li> <p>"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."</p> </li> <li> <p> "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?" </p> </li> <li> <p> "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?" </p> </li> <ul> </div> </body 

我为此写了一个相对简单的答案。

我有一个表使用“粘表表头”插件粘在我的页面上一个特定的div下面,但是表左边的菜单并没有粘住(因为它不是表格的一部分)。

对于我的目的,我知道需要“粘性”的div总是从窗口顶部的385像素开始,所以我在上面创build了一个空的div:

 <div id="stopMenu" class="stopMenu"></div> 

然后跑这个:

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

当用户滚动时,它将$(window).scrollTop()值添加到整数385 ,然后将该值添加到位于我要保持聚焦的事物上方的stopMenu div。

如果用户一直向后滚动,我只是将额外的填充设置为0。

这并不要求用户在CSS中执行任何操作,但是对于延迟时间有很好的效果,所以我把class="stopMenu"放在这里:

 .stopMenu { .transition: all 0.1s; }