我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
当前回答
那么多的答案试图计算文件的高度。但对我来说,这并不是正确的计算。然而,这两种方法都有效:
jquery
$('html,body').animate({scrollTop: 9999});
或者只是js
window.scrollTo(0,9999);
其他回答
香草JS实现:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
以下是我的解决方案:
//**** scroll to bottom if at bottom
function scrollbottom() {
if (typeof(scr1)!='undefined') clearTimeout(scr1)
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
if((scrollTop + window.innerHeight) >= scrollHeight-50) window.scrollTo(0,scrollHeight+50)
scr1=setTimeout(function(){scrollbottom()},200)
}
scr1=setTimeout(function(){scrollbottom()},200)
一个使用jquery的简单例子
$('html, body').animate({
scrollTop: $(this).height(),
});
我也遇到过同样的问题。对于我来说,在一个时间点上,div的元素没有完全加载,scrollTop属性是用scrollHeight的当前值初始化的,这不是scrollHeight的正确结束值。
我的项目在Angular 8中,我所做的是:
我使用viewchild来获取.ts文件中的元素。 我已经继承了AfterViewChecked事件,并在那里放置了一行代码,其中声明viewchild元素必须将scrollTop值的值scrollHeight (this.viewChildElement.nativeElement。scrollTop = this.viewChildElement.nativeElement.scrollHeight;)
AfterViewChecked事件触发了几次,它最终从scrollHeight中获得了正确的值。
如果在您想要滚动到的位置或附近的任何类型的标记中有一个ID,那么只需使用scrollIntoView函数编写一行JavaScript即可。例如,假设您所讨论的元素是ID为“mydiv1”的DIV
<div id="mydiv1">[your contents]</div>
然后运行JavaScript命令
document.getElementById("mydiv1").scrollIntoView();
根本不需要JQuery。 希望这能有所帮助。