jquery.scrollTo — 在页面加载时滚动

jquery.scrollTo — Scroll on Page Load

本文关键字:加载 滚动 scrollTo jquery      更新时间:2023-09-26

我在网站的各个部分使用以下jQuery插件 — https://github.com/flesler/jquery.scrollTo

我可以让它与链接正常工作,这样当单击它们时,它会滚动到页面的某个部分,如下所示:

$('#button-top').bind('click', function(e) {
    try {
        e.preventDefault();
        target = this.hash;
        $('html, body').scrollTo(target, 150);
    } catch (error) {
        alert('error - ' + error);
    }
});

但是在一个页面上,我需要它,以便在加载页面时滚动,如下所示:

if ($('.gform_validation_error').length > 0) {
    // scroll here
}

我将如何调整我的脚本,使其在页面加载时滚动,而不是在单击链接时滚动?

试试这个 - 在页面加载时使用 .ready() 函数触发

这是工作演示 - 点击这里

$(document).ready(function(){
   if ($('.gform_validation_error').length > 0) {
       var controlID ="#" + "divToScroll"; // this is ID of DIV where you want to scroll on page load.
        $('html, body').animate({
    scrollTop: $(controlID).offset().top
}, 2000);
   }
});
jQuery(document).ready(function() {
    jQuery('#target')[0].scrollIntoView();
});

这是一个小提琴来展示如何做到这一点 http://jsfiddle.net/qnr9n989/