单击按钮时,我将页面设置为滚动到顶部。但首先我使用if语句来查看页面顶部是否未设置为0.然后,如果它不是0,我会动画页面滚动到顶部。
var body = $("body");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
body.animate({scrollTop:0}, '500');
}
现在棘手的部分是在页面滚动到顶部后动画一些东西。所以我的下一个想法是,找出页面位置是什么。所以我用console log来查找。
console.log(top); // the result was 365
这给了我一个365的结果,我猜这是我在滚动到顶部之前的位置编号。
我的问题是如何将位置设置为0,以便我可以添加另一个在页面为0时运行的动画?
谢谢!
答案 0 :(得分:284)
为此,您可以为动画命令设置一个回调函数,该函数将在滚动动画完成后执行。
例如:
var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() {
alert("Finished animating");
});
警报代码在哪里,你可以执行更多的javascript来添加动画。
此外,'swing'用于设置缓和。查看http://api.jquery.com/animate/了解详情。
答案 1 :(得分:44)
试试这段代码:
$('.Classname').click(function(){
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
});
答案 2 :(得分:28)
使用此:
$('a[href^="#"]').on('click', function(event) {
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 500);
}
});
答案 3 :(得分:7)
请改为尝试:
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');
});
}
答案 4 :(得分:6)
为此你可以使用回调方法
body.animate({
scrollTop:0
}, 500,
function(){} // callback method use this space how you like
);
答案 5 :(得分:3)
点击功能代码()
var body = $('html, body');
$('.toTop').click(function(e){
e.preventDefault();
body.animate({scrollTop:0}, 500, 'swing');
});
.toTop
=点击元素的类别img
或a
答案 6 :(得分:3)
按ID或NAME滚动到任何元素:
SmoothScrollTo("#elementId", 1000);
代码:
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;
});
}
答案 7 :(得分:0)
jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() {
alert("Finished animating");
});
答案 8 :(得分:0)
$("body").stop().animate({
scrollTop: 0
}, 500, 'swing', function () {
console.log(confirm('Like This'))
}
);
答案 9 :(得分:0)
您可以同时使用CSS类或HTML id,为了保持对称性,我始终例如使用CSS类
<a class="btn btn-full js--scroll-to-plans" href="#">I’m hungry</a>
|
|
|
<section class="section-plans js--section-plans clearfix">
$(document).ready(function () {
$('.js--scroll-to-plans').click(function () {
$('body,html').animate({
scrollTop: $('.js--section-plans').offset().top
}, 1000);
return false;})
});
答案 10 :(得分:-1)
您必须看到
$(function () {$('a').click(function () {
$('body,html').animate({
scrollTop: 0
}, 600);
return false;});});
或试试
throw completion handler