简体   繁体   中英

How to constantly check whether there is div overflow and then scroll to the bottom

I'm creating a div which on overflow goes to the bottom straight away.But how do I constantly check whether an overflow has occurred or not and then fire the function which will scroll down to the bottom of the page?

I found this function which scrolls to the bottom

 <script type="text/javascript">
  var objDiv = document.getElementsByClassName('container')[0];
   objDiv.scrollTop = objDiv.scrollHeight;
 <script>

and this function which checks whether there is an overflow or not

 <script type="text/javascript">
  function isOverflown(element) {
    return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth;
     }
  </script>

But how do I constantly listen when the overflow occurs? Also, I have one more problem after always scrolling to the bottom of the page, if I manually want to go on the top, it automatically scrolls to the bottom.How do I prevent this?

For run code continues, you can use setInterval function. It takes two params, the callback , and the time in milliseconds . It runs the code all the time, so you can put there function to be executed.

If the content is dynamic you can use also callback to check that after render, it should be recalculated.

But, why do you want to do this?

Thanks to @Piotr P. I found the way to do this, but now i'm unable to scroll it manually to other parts of the screen

  setInterval(function(){
      var element = document.getElementsByClassName('container')[0];
      if (element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth) {
        $('#mydiv').animate({
                   scrollTop: $(document).height()
               },
                'slow');
               return false;
      }
    }, 100);

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