简体   繁体   English

scrollTo()函数什么都不做

[英]scrollTo() function does nothing

I wanted to scroll to the bottom of the page using vanilla JS, but I encountered a problem. 我想使用香草JS滚动到页面底部,但是遇到了问题。 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. 返回一个整数736。除此之外,我向函数参数中输入的内容都没有关系。 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. 可能重要(不确定)的是,该网站隐藏了其垂直滚动条,甚至认为它的内容列表很长。

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. 问题可能是您在网站上拥有的实际滚动条不是body的滚动条,而是该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. 注意-使用jquery只是为了使示例更短。

例如,在页面上放置一些内容,或设置主体高度= 1500px,然后尝试执行相同的代码。

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);

If you will try to type in browser's console like a var a = 5 you also will get undefined. 如果您尝试像var a = 5一样输入浏览器的控制台,您也会得到未定义的信息。 It happens that your example and my did not return anything. 碰巧您的示例和我没有返回任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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