我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。

我如何用jQuery做到这一点?


当前回答

有时页面会滚动到底部(例如在社交网络中),向下滚动到最后(页面的最终底部),我使用这个脚本:

var scrollInterval = setInterval(function() { 
    document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);

如果你是在浏览器的javascript控制台,它可能是有用的,能够停止滚动,所以添加:

var stopScroll = function() { clearInterval(scrollInterval); };

然后使用stopScroll();。

如果你需要滚动到特定的元素,使用:

var element = document.querySelector(".element-selector");
element.scrollIntoView();

或通用脚本自动滚动到特定的元素(或停止页面滚动间隔):

var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
    var element = document.querySelector(".element-selector");
    if (element) { 
        // element found
        clearInterval(scrollInterval);
        element.scrollIntoView();
    } else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) { 
        // no element -> scrolling
        notChangedStepsCount = 0;
        document.documentElement.scrollTop = document.documentElement.scrollHeight;
    } else if (notChangedStepsCount > 20) { 
        // no more space to scroll
        clearInterval(scrollInterval);
    } else {
        // waiting for possible extension (autoload) of the page
        notChangedStepsCount++;
    }
}, 50);

其他回答

window.scrollTo (0,1 e10);

总是工作。

1e10是个很大的数字。所以它总是在页面的末尾。

一个内线平滑滚动到底部

window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });

要向上滚动,只需将top设置为0

你可以给link元素的引用属性href附加任何id:

<a href="#myLink" id="myLink">
    Click me
</a>

在上面的例子中,当用户单击页面底部的“点击我”时,导航导航到“点击我”本身。

您可以使用它以动画格式向下浏览页面。

$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");

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 >