案例:带有动画的返回顶部
css样式
.box {
width: 800px;
height: 400px;
background-color: blanchedalmond;
margin: 500px auto;
}
.box2 {
position: fixed;
right: 10px;
top: 50%;
display: none;
width: 50px;
height: 50px;
background-color: red;
}
html
<div class=box></div>
<div class="box2">返回顶部</div>
jQuery代码
ps: animate 只有元素才能做动画
$(function() {
var box = $(".box").offset().top; //获取box2的头部距离
$(window).scroll(function() {
if ($(document).scrollTop() >= box) { //如果 滚动到box2的距离 就box2才会显示出来
$(".box2").css("display", "block")
} else {
$(".box2").css("display", "none")
}
})
$(".box2").click(function() {
$("body,html").stop().animate({ //animate 只能元素才能做动画
scrollTop: 0
})
})
})