scrollTo() function does nothing

不问归期 提交于 2020-06-29 13:13:08

问题


I wanted to scroll to the bottom of the page using vanilla JS, but I encountered a problem. The code below is supposed to scroll to the bottom of the page:

window.scrollTo(0,document.body.scrollHeight);

Whereas all it does is logs "undefined" in the console. Inputting

document.body.scrollHeight

returns an integer 736. Other than that, it doesn't matter what I input into the function's parameters, nothing happens. What more, it only happens on one website. What may matter (not sure) is that the website hides its vertical scrolling bar, even thought it has a really long list of content.


回答1:


The problem might be that the actuall scroll that you have on the website is not the scroll of the body but a scroll of another element inside that body.

Here is an example:

$('#btn1').click(function() {
  window.scrollTo(0,document.body.scrollHeight);
});
$('#btn2').click(function() {
  el = $('.a')[0];
  el.scrollTop = el.scrollHeight;
});
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
}
div.a {
  height: 100vh;
  overflow: auto;
}
div.b {
  height: 1500px;
  position: relative;
}
div.c {
  position: absolute;
  bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
  <div class="b">
    <button id="btn1">Scroll body - doesn't work</button><br />
    <button id="btn2">Scroll element - will work</button>
    <div class="c">This is at bottom of page</div>
  </div>
</div>

Note - the usage of jquery is only to make the example shorter.




回答2:


Solved. This is what had to be done:

document.getElementsByTagName('body')[0].style.display = "block";

For whatever reason, changing the display to "block" enabled the scrolling using the given code:

window.scrollTo(0,document.body.scrollHeight);



回答3:


If you will try to type in browser's console like a var a = 5 you also will get undefined. It happens that your example and my did not return anything.




回答4:


Put some content in your page o style the body heigth = 1500px for example, then try to execute same code.



来源:https://stackoverflow.com/questions/46018212/scrollto-function-does-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!