简体   繁体   中英

Javascript - Can I make this table scroll to top?

I have to make a self-scrolling table. I tried using this: https://codepen.io/salman31/pen/dYdGLa

    var my_time;
$(document).ready(function() {
  pageScroll();
  $("#contain").mouseover(function() {
    clearTimeout(my_time);
  }).mouseout(function() {
    pageScroll();
  });
});

function pageScroll() {  
    var objDiv = document.getElementById("contain");
  objDiv.scrollTop = objDiv.scrollTop + 1;  
  $('p:nth-of-type(1)').html('scrollTop : '+ objDiv.scrollTop);
  $('p:nth-of-type(2)').html('scrollHeight : ' + objDiv.scrollHeight);
  //if (objDiv.scrollTop == (objDiv.scrollHeight - 50)) {
    objDiv.scrollTop = 0;
  //}
  my_time = setTimeout('pageScroll()', 25);
}

And it works, but it doesn't automatically scroll back to top when it hits the "bottom". What do I need to change?

Thank you!

try this

var my_time;
$(document).ready(function() {
  pageScroll();
  $("#contain").mouseover(function() {
    clearTimeout(my_time);
  }).mouseout(function() {
    pageScroll();
  });

  $('#contain').bind('scroll', function()
     {
       if($(this).scrollTop() + $(this).innerHeight()>=$(this)[0].scrollHeight)
          {
              pageScroll();
          }
     })
});

function pageScroll() {  
    var objDiv = document.getElementById("contain");
  objDiv.scrollTop = objDiv.scrollTop + 1;  
  $('p:nth-of-type(1)').html('scrollTop : '+ objDiv.scrollTop);
  $('p:nth-of-type(2)').html('scrollHeight : ' + objDiv.scrollHeight);
  if (objDiv.scrollTop == (objDiv.scrollHeight - 100)) {
    objDiv.scrollTop = 0;
  }
  my_time = setTimeout('pageScroll()', 25);
}

The line:

objDiv.scrollTop = 0

is what's supposed to reset the scroll position, using the if statement you've got commented to execute it only once it's finished scrolling up. With the if statement commented out, the table shouldn't be scrolling at all, as the pageScroll function will always set the scrollTop property to 0.

Try uncommenting the if statement, and making sure that you're subtracting the height of your container from objDiv.scrollHeight in the comparison.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM