0

我目前正在使用平滑滚动技术从 div 滚动到 div,基本上我有一大堆 div,一个接一个,当您单击当前 div 时,它会将您带到下一个,等等。
但这就是我'我遇到了问题,因为目前我必须为每个 div 设置 # 以告诉它转到下一个。这是我的代码,它可能更有意义:
HTML:

        <a href="#slide-2"><div id="slide-1" class="slides">
            <div class="text">
ONE
            </div>
        </div></a>

         <a href="#slide-3"><div id="slide-2" class="slides">
            <div class="text">
TWO 
            </div>
        </div></a>  

        <a href="#slide-4"><div id="slide-3" class="slides">
            <div class="text">
THREE
            </div>
        </div></a>  

        <a href="#slide-5"><div id="slide-4" class="slides">
            <div class="text">
FOUR
            </div>
        </div></a>  

        <a href="#slide-6"><div id="slide-5" class="slides">
            <div class="text">
FIVE
            </div>
        </div></a>  

        <a href="#slide-7"><div id="slide-6" class="slides">
            <div class="text">
SIX
            </div>
        </div></a>

jQuery:

$(document).ready(function(){
   $('a[href*=#]').bind('click', function(e) {
    e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump

    var target = $(this).attr("href"); //Get the target

    // perform animated scrolling by getting top-position of target-element and set it as scroll target
    $('html, body').stop().animate({ scrollTop: $(target).offset().top }, 400, function() {
         location.hash = target;  //attach the hash (#jumptarget) to the pageurl
    });

    return false;
   });
});

如您所见,幻灯片 1 的 href 将您带到幻灯片 2,依此类推,但最后会有很多 div,随着时间的推移会添加更多,所以我想知道是否有一种从 div 滚动到 div 的更简单方法,即有没有一种方法可以检测下一个 div 并滚动到它等等?

4

2 回答 2

2

You can add classes to the a elements and use next and find methods.

$(document).ready(function(){
   $('a.className').on('click', function(e) {
      e.preventDefault(); 
      var offset = $(this).next().find('div').offset().top;
      $('html, body').stop().animate({ scrollTop: offset }, 400);
   });
});

You can also select the elements and cache the objects:

$(document).ready(function(){
   var $a = $('a.className'), $targets = $('div.targets');
   $a.on('click', function(e) {
      e.preventDefault(); 
      var i = $a.index(this);
      var offset = $targets.eq(++i).offset().top;
      $('html, body').stop().animate({ scrollTop: offset }, 400);
   });
});
于 2013-01-29T13:20:49.853 回答
-1

获取您的 div 的索引并滑动到下一个。

$(".linkToNextDiv").click(function(e)
{
    var parent = $(this).parent("div");
    var index = $(parent).index();
    scrollToDiv(index+1);
});

This is just a generic example. You'll need to adapt it to your code.

于 2013-01-29T13:20:44.903 回答