自动滚动到每个div或元素

时间:2014-02-28 01:03:25

标签: javascript jquery css html

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

假设这是我的页面结构..

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

- 现在假设我的每个div都有足够的内容来使页面变长。假设用户在my-div-1上,当观众使用滚动按钮向下滚动时,我想让它自动滚动到my-div-2。

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

有没有办法通过使用javascript和jquery来解决它?

我将不胜感激任何回应......谢谢。

1 个答案:

答案 0 :(得分:2)

这里有你想要的小提琴:http://jsfiddle.net/3qxhY/9/

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

<强>代码

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