如何使用 JQuery $. scrollTo()函数滚动窗口

我试图向下滚动100px 每次用户接近顶部的文件。

当用户接近文档顶部时,函数将执行,但是。ScrollTo 函数不工作。

我在之前和之后都设置了一个警报,看看是不是那行真的阻止了它,只有第一个警报响了,下面是代码:

alert("starting");
$.scrollTo({ top: '+=100px', left: '+=0px' }, 800);
alert("finished");

我知道我已经正确地链接了 jquery 页面,因为我在整个过程中使用了许多其他的 jquery 函数,它们都工作得很好。我也试过去掉上面的“ px”,但似乎没有什么效果。

270677 次浏览

Looks like you've got the syntax slightly wrong... I'm assuming based on your code that you're trying to scroll down 100px in 800ms, if so then this works (using scrollTo 1.4.1):

$.scrollTo('+=100px', 800, { axis:'y' });

If it's not working why don't you try using jQuery's scrollTop method?

$("#id").scrollTop($("#id").scrollTop() + 100);

If you're looking to scroll smoothly you could use basic javascript setTimeout/setInterval function to make it scroll in increments of 1px over a set length of time.

jQuery now supports scrollTop as an animation variable.

$("#id").animate({"scrollTop": $("#id").scrollTop() + 100});

You no longer need to setTimeout/setInterval to scroll smoothly.

$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);

Actually something like

function scrollTo(prop){
$('html,body').animate({scrollTop: $("#"+prop).offset().top +
parseInt($("#"+prop).css('padding-top'),10) },'slow');
}

will work nicely and support padding. You can also support margins easily - for completion see below

function scrollTo(prop){
$('html,body').animate({scrollTop: $("#"+prop).offset().top
+ parseInt($("#"+prop).css('padding-top'),10)
+ parseInt($("#"+prop).css('margin-top'),10) +},'slow');
}

To get around the html vs body issue, I fixed this by not animating the css directly but rather calling window.scrollTo(); on each step:

$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
duration: 600,
easing: 'swing',
step: function(val) {
window.scrollTo(0, val);
}
});

This works nicely without any refresh gotchas as it's using cross-browser JavaScript.

Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.