首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自动滚动到每个div或元素

自动滚动到每个div或元素
EN

Stack Overflow用户
提问于 2014-02-28 01:03:24
回答 1查看 1.9K关注 0票数 0

当用户使用鼠标中的滚动按钮时,我需要一些关于自动滚动到每个div或元素的帮助。接下来的场景是

假设这是我的页面结构。

代码语言:javascript
复制
<div id="main-wrap">

<div class="my-div-1">
    <p>here goes my content 1</p>
    <img src="/images/sample-1" alt="sample-1"/>

</div>

<div class="my-div-2">

<p>here goes my content 2</p>
<img src="/images/sample-2" alt="sample-2"/>

</div>

<div class="my-div-3">

<p>here goes my content 3</p>
<img src="/images/sample-3" alt="sample-3"/>

</div>

</div><!-- end of main-wrap id -->

-Now假设我的每个div都有足够的内容来使页面变长。假设用户在my- div -1上,当查看器使用滚动按钮向下滚动,而不是滚动整个div时,我希望它自动滚动到my-div-2。

我希望我的解释在这里有意义。

有没有办法通过使用javascript和jquery来解决这个问题?

我将感谢任何response..Thanks在事先。

EN

回答 1

Stack Overflow用户

发布于 2014-02-28 03:18:34

这里有一个摆弄你想要的:http://jsfiddle.net/3qxhY/9/

代码中使用的插件的来源(拆下/节流插件):http://benalman.com/projects/jquery-throttle-debounce-plugin/

代码语言:javascript
复制
// debounce/throttle plugin
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);

//elements you want to scroll to go here
divs = [$(".my-div-1"),$(".my-div-2"),$(".my-div-3")];

var lastScrollTop = 0; //we'll update this on every scroll and compare it to the last scroll to determine the scroll direction
var run = true;

$(window).scroll($.debounce(250, true, function () { //debounce so it only runs once per scroll
  var st = $(window).scrollTop();
  if (st > lastScrollTop) { // if the scrollTop when the scroll event fires is larger than the last scroll, we can assume the scroll was in a downward direction
    $.each(divs, function (i, v) {
      ((v.offset().top - $(window).scrollTop()) < 0) && (next = i + 1); //compare each elements offset to the windows offset to determine which element we're currently scrolling through
    });      
    run = (next != divs.length) ? true : false; //dont run if we are at the last div
  } else {
    $.each(divs, function (i, v) {
      ((v.offset().top - $(window).scrollTop()) < 0) && (next = i);
    }); 
    run = true;
  }
  if (run) {
    $('html, body').animate({
      scrollTop: divs[next].offset().top
    }, 1000,'linear', function() {
      lastScrollTop = $(window).scrollTop();
    });
  } else { lastScrollTop = $(window).scrollTop(); }
}));
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22084148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档