Jquery ScrollTop将ID + SetTimeout倍增

时间:2016-03-15 04:24:00

标签: javascript jquery

这是我的情况,根据文件夹中存在的pdf文件的数量,我有一个页面,其中包含从php while循环创建的mutiples div / id。我的目标是每5秒滚动到每个ID,然后从头开始重新滚动。以下代码工作正常,但问题是,如果我将5个新文件添加到该文件夹​​,那么我需要复制五次该功能,我要找的是滚动以便文档上的所有可用ID。有没有办法写一个函数来做到这一点?任何灯都将被赞赏。

这是我的实际代码:

$(document).ready(function () {

        function loopanchors() {

            setTimeout(function () {
                $('html, body').animate({
                    'scrollTop': $('#1').offset().top
                }, 2000);
            }, <?php echo $pdf_time; ?>);

            setTimeout(function () {
                $('html, body').animate({
                    'scrollTop': $('#2').offset().top
                }, 2000);
            }, <?php echo $pdf_time*2; ?>);

            setTimeout(function () {
                $('html, body').animate({
                    'scrollTop': $('#3').offset().top
                }, 2000);
            }, <?php echo $pdf_time*3; ?>);

            setTimeout(function () {
                $('html, body').animate({
                    'scrollTop': $('#4').offset().top
                }, 2000);
            }, <?php echo $pdf_time*4; ?>);

            setTimeout(function () {
                $('html, body').animate({
                    'scrollTop': $('#5').offset().top
                }, 2000);
            }, <?php echo $pdf_time*5; ?>);

            setTimeout(function () {
                $('html, body').animate({
                    'scrollTop': $('#6').offset().top
                }, 2000);
            }, <?php echo $pdf_time*6; ?>);

            setTimeout(function () {
                $('html, body').animate({
                    'scrollTop': $('#7').offset().top
                }, 2000);
            }, <?php echo $pdf_time*7; ?>);

            x = setTimeout(function () {
                loopanchors()
            }, <?php echo $pdf_time*8; ?>); //will loop every 5 seconds.
        }

        loopanchors(); //start it up the first time

    });

1 个答案:

答案 0 :(得分:2)

试试此代码调整$ pdf_time&amp; totalPDF根据您的需要:

<script>
  var totalPDF = 7;
  var currentPDF = 0;
  var loopInterval = <?php echo $pdf_time; ?>;
  $(function(){
    function loopanchors(){
      if(totalPDF <= currentPDF++){
        currentPDF = 1;
      }

      /* scroll to currentPDF */
      setTimeout(function(){
        console.log('scrolling to', currentPDF);
        try{
          $('html, body').animate({
            scrollTop: $('#' + currentPDF).offset().top
          },
          2000);
        }catch(e){
          console.log('element not found');
        }

        /* scroll next pdf */
        loopanchors();
      }, (loopInterval * currentPDF));
    }

    /*start it up the first time*/
    loopanchors();
  });
</script>