我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
当前回答
香草JS实现:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
其他回答
如果您想向下滚动到特定元素,这是一种简单的方法。
当您想向下滚动时,请调用此函数。
function scrollDown() { document.getElementById('scroll').scrollTop = document.getElementById('scroll').scrollHeight } ul{ height: 100px; width: 200px; overflow-y: scroll; border: 1px solid #000; } <ul id='scroll'> <li>Top Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Bottom Here</li> <li style="color: red">Bottom Here</li> </ul> <br /> <button onclick='scrollDown()'>Scroll Down</button>
香草JS实现:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
这里有一个对我有用的方法:
预期结果:
无滚动动画 在第一次加载页面底部加载 加载在页面底部的所有刷新
代码:
<script>
function scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
history.scrollRestoration = "manual";
window.onload = scrollToBottom;
</script>
为什么这种方法比其他方法更有效:
像Chrome这样的浏览器有一个内置的预设,可以在刷新后记住你在页面上的位置。只是一个窗口。onload不起作用,因为你的浏览器会自动滚动你在刷新之前的位置,在你调用一行后,如:
window.scrollTo(0, document.body.scrollHeight);
这就是为什么我们需要补充:
history.scrollRestoration = "manual";
在窗户前。Onload首先禁用该内置功能。
引用:
窗口的文档。onload: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
窗口的文档。scrollTo: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
历史文档。scrollRestoration: https://developer.mozilla.org/en-US/docs/Web/API/History/scrollRestoration
这将保证滚动到底部
头代码
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script language="javascript" type="text/javascript">
function scrollToBottom() {
$('#html, body').scrollTop($('#html, body')[0].scrollHeight);
}
</script>
机构代码
<a href="javascript:void(0);" onmouseover="scrollToBottom();" title="Scroll to Bottom">▼ Bottom ▼</a>
下面是跨浏览器的解决方案。它已经在Chrome、Firefox、Safari和IE11上进行了测试
window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
window.scrollTo (0, document.body.scrollHeight);不能在Firefox上运行,至少不能在Firefox 37.0.2上运行