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

我如何用jQuery做到这一点?


当前回答

那么多的答案试图计算文件的高度。但对我来说,这并不是正确的计算。然而,这两种方法都有效:

jquery

    $('html,body').animate({scrollTop: 9999});

或者只是js

    window.scrollTo(0,9999);

其他回答

我放弃了滚动,而是尝试了锚定方法:

<a href="#target_id_at_bottom">scroll to the bottom</a>

伴随着这个CSS魅力:

html,
body {
    scroll-behavior: smooth;
}

祝你有愉快的一天!

香草JS实现:

element.scrollIntoView(false);

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

你可以试试Gentle Anchors,一个不错的javascript插件。

例子:

function SomeFunction() {
  // your code
  // Pass an id attribute to scroll to. The # is required
  Gentle_Anchors.Setup('#destination');
  // maybe some more code
}

兼容性测试对象:

Mac Firefox, Safari, Opera Windows Firefox, Opera, Safari, Internet Explorer 5.55+ Linux未经测试,但至少Firefox应该没问题

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

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

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

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

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);