如何使用jQuery在页面上滚动到特定位置?

135

使用 jQuery 可以将页面滚动到特定位置吗?

我想要滚动到的位置必须具备什么条件吗?

<a name="#123">here</a>

或者它只能移动到特定的DOM id吗?


3
只是一张小便签:在 XHTML 1.1 Strict 中不允许使用属性 "name",请改用 ID。 - Juraj Blahunka
有趣的问题,不能使用页面坐标来滚动吗?我认为我们应该能够做到。 - Omar Abid
我在这里找到了与你需求类似的解决方案。 - user1493023
@mrblah 你的问题解决了吗? - Meghdad Hadidi
11个回答

242

jQuery滚动插件

由于这是一个带有jquery标签的问题,我必须说,这个库有一个非常好用的平滑滚动插件,你可以在这里找到它: http://plugins.jquery.com/scrollTo/

来自文档的摘录:

$('div.pane').scrollTo(...);//all divs w/class pane
或者
$.scrollTo(...);//the plugin will take care of this

自定义jQuery滚动函数

你可以通过定义自己的自定义滚动jQuery函数,使用非常轻量级的方法

$.fn.scrollView = function () {
    return this.each(function () {
        $('html, body').animate({
            scrollTop: $(this).offset().top
        }, 1000);
    });
}

并像这样使用:

$('#your-div').scrollView();

滚动到页面坐标

使用 scrollTopscrollLeft 属性使 htmlbody 元素动画滚动

$('html, body').animate({
    scrollTop: 0,
    scrollLeft: 300
}, 1000);

纯JavaScript

使用window.scroll进行滚动

window.scroll(horizontalOffset, verticalOffset);

总之,使用window.location.hash可以跳转到具有ID的元素

window.location.hash = '#your-page-element';

直接在HTML中实现(可访问性增强)

<a href="#your-page-element">Jump to ID</a>

<div id="your-page-element">
    will jump here
</div>

谢谢@Juraj Blahunka,但我不使用任何插件来完成这个。 - Meghdad Hadidi
链接没有带我到ScrollTo。你能更新一下吗? - Barnee
这应该是答案! - neelmeg

130

没错,即使在纯JavaScript中也很容易。你给一个元素指定一个id,然后就可以将其作为"书签"使用:

是的,在普通的JavaScript中,这非常简单。你给一个元素指定一个ID,然后就可以将它作为"书签"使用:

<div id="here">here</div>

如果你希望当用户点击链接时它可以自动滚动到那里,你可以使用经过验证的传统方法:

<a href="#here">scroll to over there</a>

如果要以编程方式完成此操作,请使用scrollIntoView()

document.getElementById("here").scrollIntoView()

@nickf 这还不是到处都支持的。http://caniuse.com/#search=scrollIntoView - Aditya Singh
这是被支持的 (https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView)。我认为你没有仔细阅读 caniuse 的内容。然而,它不会有动画效果,而是一个相当突兀的跳转,这并不总是很好。 - perry

56

无需使用任何插件,您可以像这样操作:

var divPosition = $('#divId').offset();

然后使用此代码将文档滚动到指定的DOM:

$('html, body').animate({scrollTop: divPosition.top}, "slow");

3
这可能是最好的答案。代码不多,也不需要插件。 - Tricky12
1
请注意,在窗口调整大小时,您可能需要重新计算偏移量。 - Bart Burg
2
@BartBurg 说得好--或者就在.animate调用发生之前重新计算。 - mikermcneil
5
爱简单的答案。为什么人们要把事情搞得这么复杂?不想再安装另一个插件。 - sterfry68
1
确实是最佳答案。 - Robert Ross

21

这是一个纯 JavaScript 版本:

location.hash = '#123';

它将自动滚动。 记得添加 "#" 前缀。


1
使用命名锚点的原始方式,您可以拥有包含哈希的URL,例如http://www.mywebsite.com/page-about/#123 书签也包括哈希+滚动到视图行为。 - o.k.w
1
如果你能解释一下,那就太好了。 - JGallardo

7

纯JavaScript:

window.location = "#elementId"

6
<div id="idVal">
    <!--div content goes here-->
</div>
...
<script type="text/javascript">
     $(document).ready(function(){
         var divLoc = $('#idVal').offset();
         $('html, body').animate({scrollTop: divLoc.top}, "slow");
     });
</script>

这个例子展示了如何定位到特定的div id,比如这里的'idVal'。如果你有其他通过ajax在页面上打开的后续divs/tables,那么你可以为每个div内容分配唯一的div并调用脚本来滚动到特定位置。
希望这对你有帮助。

4
<script type="text/javascript">
    $(document).ready(function(){
        $(".scroll-element").click(function(){
            $('html,body').animate({
                scrollTop: $('.our_companies').offset().top
            }, 1000);

            return false;
        });
    })
</script>


如果您在代码中添加一些注释,那将是非常好的。这如何帮助提问者解决他们的问题呢? - Artemix

1

试试这个

<div id="divRegister"></div>

$(document).ready(function() {
location.hash = "divRegister";
});

0
这是@juraj-blahunka的轻量级方法的变体。此函数不假定容器为文档,仅在项目超出视图时滚动。动画排队也已禁用,以避免不必要的弹跳。
$.fn.scrollToView = function () {
    return $.each(this, function () {
        if ($(this).position().top < 0 ||
            $(this).position().top + $(this).height() > $(this).parent().height()) {
            $(this).parent().animate({
                scrollTop: $(this).parent().scrollTop() + $(this).position().top
            }, {
                duration: 300,
                queue: false
            });
        }
    });
};

我遇到了反弹问题,但是你的方法不起作用。 - Anon

0
使用jquery.easing.min.js,修复IE控制台错误 HTML
<a class="page-scroll" href="#features">Features</a>
<section id="features" class="features-section">Features Section</section>


        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="js/jquery.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Scrolling Nav JavaScript -->
        <script src="js/jquery.easing.min.js"></script>

Jquery

//jQuery to collapse the navbar on scroll, you can use this code with in external file with name scrolling-nav.js
        $(window).scroll(function () {
            if ($(".navbar").offset().top > 50) {
                $(".navbar-fixed-top").addClass("top-nav-collapse");
            } else {
                $(".navbar-fixed-top").removeClass("top-nav-collapse");
            }
        });
        //jQuery for page scrolling feature - requires jQuery Easing plugin
        $(function () {
            $('a.page-scroll').bind('click', function (event) {
                var anchor = $(this);
                if ($(anchor).length > 0) {
                    var href = $(anchor).attr('href');
                    if ($(href.substring(href.indexOf('#'))).length > 0) {
                        $('html, body').stop().animate({
                            scrollTop: $(href.substring(href.indexOf('#'))).offset().top
                        }, 1500, 'easeInOutExpo');
                    }
                    else {
                        window.location = href;
                    }
                }
                event.preventDefault();
            });
        });

这个简单的任务需要的代码太多了。只需要 location.hash = 'idOfElement'; 就可以了。 - Kellen Stuart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接