我有一个可以上下滚动的 HTML 页面(不是很多,但确实可以滚动)。执行一些 JavaScript 后如何设置页面中的滚动位置?

我正在使用 jQuery 在页面底部注入一些额外的 HTML,并且我想在添加新内容后以编程方式滚动到新内容的位置。

有帮助吗?

解决方案

另一种方法可以做到这一点,以便您可以选择:

在添加到页面底部的 HTML 中,您可以插入命名锚标记,然后更改 URL,以便页面移动到那里(仅供​​参考:它不会刷新页面)。

// add HTML like this, dynamically:
// <a name="moveHere" />

// the javascript to make the page go to that location:
window.location.hash = "moveHere";

根据您正在做的事情,这可能是也可能不是一个有用的解决方案。

其他提示

尝试使用 window.scroll

  

示例:

// put the 100th vertical pixel at the top of the window
<button onClick="scroll(0, 100);">click to scroll down 100 pixels</button>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top