我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
当前回答
CSS-Only ? !
一个有趣的css替代方案:
display: flex;
flex-direction: column-reverse;
/* ...probably usually along with: */
overflow-y: scroll; /* or hidden or auto */
height: 100px; /* or whatever */
它不是万无一失的,但我发现它在一些情况下很有帮助。
文档:flex, flex-direction, overflow-y
演示:
var i=0, foo='Lorem Ipsum & foo在酒吧或blah !和“。分割(' '); setInterval(函数(){demo.innerHTML + = foo [i + + % foo。长度)+ ' '},200) #{演示显示:flex; flex-direction: column-reverse; overflow-y:滚动; 宽度:150 px; 身高:150 px; 边框:3px纯黑色;} 身体{字体类型:arial,无衬线; 字体大小:15 px;} Autoscrolling演示:& # x1f43e; < div id =“演示”> < / div >
其他回答
那么多的答案试图计算文件的高度。但对我来说,这并不是正确的计算。然而,这两种方法都有效:
jquery
$('html,body').animate({scrollTop: 9999});
或者只是js
window.scrollTo(0,9999);
你可以给link元素的引用属性href附加任何id:
<a href="#myLink" id="myLink">
Click me
</a>
在上面的例子中,当用户单击页面底部的“点击我”时,导航导航到“点击我”本身。
滚动整个页面到底部:
const scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;
你可以在这里查看演示
将一个特定的元素滚动到底部:
const scrollToBottom = (id) => {
const element = document.getElementById(id);
element.scrollTop = element.scrollHeight;
}
下面是演示
它是这样工作的:
参考:scrollTop, scrollHeight, clientHeight
更新:最新版本的Chrome(61+)和Firefox不支持滚动正文,请参阅:https://dev.opera.com/articles/fixing-the-scrolltop-bug/
以下是我的解决方案:
//**** 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)
香草JS实现:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView