Jua*_*ego 166 jquery scrolltop jquery-animate
单击按钮时,我将页面设置为滚动到顶部.但首先我使用if语句来查看页面顶部是否未设置为0.然后,如果它不是0,我会动画页面滚动到顶部.
var body = $("body");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
body.animate({scrollTop:0}, '500');
}
Run Code Online (Sandbox Code Playgroud)
现在棘手的部分是在页面滚动到顶部之后动画一些东西.所以我的下一个想法是,找出页面位置是什么.所以我用console log来查找.
console.log(top); // the result was 365
Run Code Online (Sandbox Code Playgroud)
这给了我一个365的结果,我猜这是我在滚动到顶部之前的位置编号.
我的问题是如何将位置设置为0,以便我可以添加另一个在页面为0时运行的动画?
谢谢!
小智 298
为此,您可以为animate命令设置一个回调函数,该函数将在滚动动画完成后执行.
例如:
var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() {
alert("Finished animating");
});
Run Code Online (Sandbox Code Playgroud)
警报代码的位置,您可以执行更多的javascript以添加进一步的动画.
此外,'swing'用于设置宽松.查看http://api.jquery.com/animate/了解更多信息.
Sha*_*esh 47
试试这段代码:
$('.Classname').click(function(){
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
});
Run Code Online (Sandbox Code Playgroud)
Bee*_*eep 30
用这个:
$('a[href^="#"]').on('click', function(event) {
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 500);
}
});
Run Code Online (Sandbox Code Playgroud)
试试这个:
var body = $("body, html");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
body.animate({scrollTop :0}, 500,function(){
//DO SOMETHING AFTER SCROLL ANIMATION COMPLETED
alert('Hello');
});
}
Run Code Online (Sandbox Code Playgroud)
为此你可以使用回调方法
body.animate({
scrollTop:0
}, 500,
function(){} // callback method use this space how you like
);
Run Code Online (Sandbox Code Playgroud)
按 ID 或 NAME 滚动到任何元素:
SmoothScrollTo("#elementId", 1000);
Run Code Online (Sandbox Code Playgroud)
代码:
function SmoothScrollTo(id_or_Name, timelength){
var timelength = timelength || 1000;
$('html, body').animate({
scrollTop: $(id_or_Name).offset().top-70
}, timelength, function(){
window.location.hash = id_or_Name;
});
}
Run Code Online (Sandbox Code Playgroud)