简体   繁体   English

JavaScript scrollTo 方法什么都不做?

[英]JavaScript scrollTo method does nothing?

So I am desperatley trying to get some scrolling functionality to work on a page.所以我绝望地试图让一些滚动功能在页面上工作。 After not having a luck I decide to just stick window.scrollTo(0, 800);在没有运气之后我决定坚持window.scrollTo(0, 800); on my page to see if I could get any scrolling to happen.在我的页面上查看是否可以进行任何滚动。 Nothing does happen.没有任何事情发生。 I have an accordion that expands and then I want to scroll to a specific element with in it.我有一个展开的手风琴,然后我想滚动到其中的特定元素。 But for now I would be happy to just see the thing scroll at all.但是现在我很乐意看到这个东西滚动。 Anyone run into this?有人遇到这个吗?

Thanks!谢谢!

If you have something like this:如果你有这样的事情:

html, body { height: 100%; overflow:auto; }

If both body and html have a height definition of 100% and also scrolling enabled, window.scrollTo (and all derived scrolling mechanisms) do not work, despite a scrollbar being displayed (which can be used by the user), when the contents exceed that 100% body height.如果 body 和 html 的高度定义都为 100% 并且启用了滚动,则 window.scrollTo(和所有派生的滚动机制)不起作用,尽管显示滚动条(用户可以使用),当内容超过那个100%的身高。 This is because the scrollbar you see is not that of the window, but that of the body.这是因为您看到的滚动条不是窗口的滚动条,而是正文的滚动条。

Solution:解决方案:

html { height: 100%; overflow:auto; }
body { height: 100%; }

I fixed this problem with using a setTimout.我使用 setTimout 解决了这个问题。 I was using angularjs but maybe it can help in vanilla js too.我正在使用 angularjs 但也许它也可以帮助 vanilla js。

        setTimeout(function () {
            window.scrollTo(0, 300);
        },2);

I was able to resolve this problem using jQuery method animate().我能够使用 jQuery 方法 animate() 解决这个问题。 Here is an example of the implementation I went with:这是我使用的实现示例:

$('#content').animate({ scrollTop: elementOffset }, 200);

The selector is getting the div with ID = "content".选择器正在获取 ID = "content" 的 div。 I am then applying the animate method on it with scrollTop as an option.然后我将 animate 方法应用于其上,并使用 scrollTop 作为选项。 The second parameter is the time in milliseconds for the animation duration.第二个参数是以毫秒为单位的动画持续时间。 I hope this helps someone else.我希望这对其他人有帮助。

Sometimes it's not just the CSS issue, for me the browser was the culprit.有时不仅仅是 CSS 问题,对我来说浏览器是罪魁祸首。 I had to solve it with this code:我不得不用这个代码解决它:

if ('scrollRestoration' in window.history) {
  window.history.scrollRestoration = 'manual'
}

It lets developer take the ownership of scroll changes.它让开发人员拥有滚动更改的所有权。 Read more about it here 在此处阅读更多相关信息

This happened to me yesterday because I had overflow: auto on a div that was a child to <html> and <body> .昨天这发生在我身上,因为我在<html><body>的子节点上有overflow: auto

So I learned that for window.scrollTo() to work, you must have overflow: auto (or whatever, overflow-y: scroll ) set on the <html> element.所以我了解到,要使window.scrollTo()工作,您必须在<html>元素上设置overflow: auto (或其他任何内容, overflow-y: scroll )。

I learned that for document.body.scrollTo() to work, you must have overflow set on <body> .我了解到要使document.body.scrollTo()工作,您必须在<body>上设置overflow

I learned you can also use it on any other element (if you want) using document.querySelector('#some-container').scrollTo() .我了解到您还可以使用document.querySelector('#some-container').scrollTo()在任何其他元素(如果需要)上使用它。

In my case, I wanted window.scrollTo() to work, so I put the overflow CSS on <html> .就我而言,我希望window.scrollTo()起作用,所以我将溢出 CSS 放在<html>

I'm surprised no other answers in here talk about "exactly which" element is scrollable.我很惊讶这里没有其他答案谈论“确切哪个”元素是可滚动的。 The root html element must be scrollable for window.scrollTo() to work.根 html 元素必须是可滚动的, window.scrollTo()才能工作。 All my child elements downstream of <html> are set to height: auto . <html>下游的所有子元素都设置为height: auto

My CSS is like this:我的 CSS 是这样的:

html { position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: auto; }
body { width: 100%; height: auto; }
#app { width: 100%; height: auto; }

I had this same problem.Focusing window before scrollTo worked for me.我有同样的问题。在 scrollTo 为我工作之前聚焦窗口。

window.focus();
window.scrollTo(0,800);

TL;DR长话短说

document.querySelector('#dummy_element').scrollIntoView()

worked for me.为我工作。

Explanation解释

I too was having an issue with the following我也有以下问题

document.querySelector('#some-container').scrollTo()

window.scrollTo()

as @agm1984 mentioned here :正如这里提到的@agm1984:

I then tried using: document.querySelector('#dummy_element').scrollIntoView()然后我尝试使用: document.querySelector('#dummy_element').scrollIntoView()

that worked out for me.这对我有用。

Differences are explained here in a better way.这里以更好的方式解释了差异。

Quick difference:快速区别:

Element.scrollIntoView() method scrolls the element on which it's called into the Viewport of the browser window. Element.scrollIntoView() 方法将调用它的元素滚动到浏览器的视口中 window。

Window.scrollTo() method scrolls to a particular set of coordinates in the document. Window.scrollTo() 方法滚动到文档中的一组特定坐标。

对我来说,将 html 和 body 的高度设置为 auto 就成功了。

html, body { height: auto }

This is what I do on React, as I have a root element, as the first and outer most div on my page, I scroll to the top of that element.这就是我在 React 上所做的,因为我有一个根元素,作为页面上第一个也是最外面的 div,我滚动到该元素的顶部。

      const root = document.getElementById('root');
      root.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth',
      });

I had this problem and it had nothing to do with these answers.我遇到了这个问题,与这些答案无关。 The problem for me first appeared after upgrading to Bootstrap 4 which converted a lot of my divs over to display: flex .在升级到 Bootstrap 4 后,我的问题首先出现,它将我的很多 div 转换为display: flex It turns out JQuery's scrollTop() doesn't work so well with flex layouts.事实证明,JQuery 的scrollTop()在 flex 布局中不能很好地工作。

The solution for me was to change my old code from:我的解决方案是更改我的旧代码:

$("#someId").scrollTop(1000);

// or

$("#someId").animate({ scrollTop: 1000 }, 500);

to

$("html,#someId").scrollTop(1000);

// or

$("html,#someId").animate({ scrollTop: 1000 }, 500);

The only difference is adding in the "html," before the div that needs to scroll.唯一的区别是在需要滚动的 div 之前添加“html”。

Props to this issue for helping me figure it out.帮助我解决这个问题的道具。

I was having this same problem today and then I discovered that when I took out the auto generated doctype block:我今天遇到了同样的问题,然后我发现当我取出自动生成的 doctype 块时:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

The window.scrollTo(0,800) started working along with the ExtJs scrollTo() function I was originally trying to use. window.scrollTo(0,800) 开始与我最初尝试使用的 ExtJs scrollTo() 函数一起工作。 I put the block back in and it stopped working.我把块放回去,它停止工作。 I don't know if this is what you were running into (2 years ago) but hopefully this helps someone else running into the same problem.我不知道这是否是您遇到的问题(2 年前),但希望这可以帮助其他人遇到同样的问题。

check if your tag where is plugged your scroll get a CSS overflow[/-xy] : hidden.检查您的标签是否插入您的滚动条是否出现 CSS 溢出 [/-xy] : hidden。 it fixed the bug它修复了错误

In my case: window.scrollBy(0,200);就我而言: window.scrollBy(0,200); is working.工作中。

I have no idea WHY window.scrollTo(0,200);我不知道为什么window.scrollTo(0,200); is not working and window.scrollBy(0,200);不工作和window.scrollBy(0,200); is working.工作中。

document.body.scrollTo(0, 800)这解决了我的问题。

First, is you page even big enough to scroll (even if it's in an iframe)?首先,您的页面是否足够大以滚动(即使它在 iframe 中)? If not, or you aren't sure, make a giant div, then put something below it.如果没有,或者你不确定,做一个巨大的 div,然后在它下面放一些东西。 Try scrolling to that.尝试滚动到那个。

Next, if your scrolling in an iframe, put your code on the same page as the frame source.接下来,如果您在 iframe 中滚动,请将您的代码与框架源放在同一页面上。 That way you don't have to worry about getting the document or specific element in the other window, which can be tricky.这样您就不必担心在另一个窗口中获取文档或特定元素,这可能很棘手。 Oh yeah, are you sure you are getting that part right?哦,是的,你确定你做对了那部分吗? Stepping through with Firebug can help you with that.逐步使用 Firebug 可以帮助您解决这个问题。

Finally, put a breakpoint (using Firebug) on the line that is supposed to cause the scrolling to happen.最后,在应该导致滚动发生的行上放置一个断点(使用 Firebug)。 Does it hit that breakpoint?它是否达到该断点? If not, your code is not executing, and scrolling is not your problem.如果没有,您的代码没有执行,滚动不是您的问题。

(I answered this, with supporting context from your earlier question .) (我回答了这个,并提供了您之前问题的支持上下文。)

EDIT:编辑:

Scrolling is done window by window.滚动是一个窗口一个窗口地完成的。 If you are in a frame that can't scroll, then nothing will scroll.如果您处于无法滚动的框架中,则不会滚动。 If you want that element in the frame to be scrolled to, get the offset of that element to its current window and add it to the offset of the containing frame.如果要滚动到框架中的该元素,请获取该元素与其当前窗口的偏移量并将其添加到包含框架的偏移量。 That should do the trick.这应该够了吧。

如果向下滑动后滚动已经完成,它应该等待div完成这样的动画

$('#div-manual-lots').slideDown(200, function () { $("html, body").animate({ scrollTop: $(document).height() }, 1000) });

使用 onunload 属性对我有用

window.onunload = function(){ window.scrollTo(0,0); }

In a React app, wrapping window.scrollTo with a setTimeout worked.在 React 应用程序中,使用 setTimeout 包装 window.scrollTo 有效。

useEffect(() => {
  if (scrollPosition > 0) {
    setTimeout(() => window.scrollTo(0, scrollPosition), 0);
    setScrollPosition(0);
  }
}, [scrollPosition]);

If for some reason both如果由于某种原因两者

   html,body {overflow: hidden}

have to be set, you could still scroll programatically with:必须设置,您仍然可以通过以下方式以编程方式滚动:

   document.body.scrollTop = document.body.scrollHeight; // scrolls to bottom
   document.body.scrollTop = 0; // scrolls to top

When window.scrollTo(x,y) does not work on the console of the Browser, and the dom gets rendered after scroll, you can use this.window.scrollTo(x,y)在浏览器的控制台上不起作用,并且在滚动后呈现 dom 时,您可以使用它。

To scroll on Splash or any javascript rendering service execute below js:要在Splash或任何javascript 渲染服务上滚动,请在 js 下执行:

document.body.style.height = "2000px";
window.scrollTo(0,2000);

In Splash you can do something similar to this:Splash 中,您可以执行类似的操作:

  assert(splash:wait(10))
  assert(splash:runjs("document.body.style.height = '2000px';"))
    assert(splash:runjs("window.scrollTo(0,2000);"))
  assert(splash:wait(2))
  assert(splash:runjs("window.scrollTo(0,0);"))

Well obviously it won't scroll if your page is not at least (viewport.height - 800) tall. 显然,如果您的页面至少(viewport.height - 800)很高,它将不会滚动。 Do you see a scroll bar? 你看到滚动条吗? Otherwise you are doing something else wrong. 否则你做错了什么。

Take this code: http://www.java2s.com/Code/JavaScriptReference/Javascript-Methods/scrollToExample.htm and save as an html file.获取此代码: http : //www.java2s.com/Code/JavaScriptReference/Javascript-Methods/scrollToExample.htm并另存为 html 文件。 Note how it hard codes a very large div larger than the browser's viewport.请注意它如何硬编码一个比浏览器视口大的非常大的 div。 You probably need to add a content at the bottom of your page for the scrolling to even work.您可能需要在页面底部添加内容才能使滚动正常工作。

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

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