jQuery实现返回顶部

时间:2023-03-09 09:06:21
jQuery实现返回顶部

由于项目需要,写了个返回顶部的小功能...

     /*返回顶部*/
function toTop() {
$(".to_top").hide();
$(window).scroll(function(){
var scroll_top = $(document).scrollTop();
if(scroll_top != 0){
$(".to_top").show();
}else{
$(".to_top").hide();
}
});
$(".to_top").click(function(){
$("body,html").animate({scrollTop:0},500);
$(".to_top").hide(); });
$(".to_top").mouseover(function(){
$(".to_top").css({
"filter":"alpha(opacity=70)",
"-moz-opacity":"0.7",
"opacity":"0.7"
});
return false;
});
$(".to_top").mouseout(function(){
$(".to_top").css({
"filter":"alpha(opacity=50)",
"-moz-opacity":"0.5",
"opacity":"0.5"
});
return false;
});
}
toTop();

值得注意的是scrollTop()方法:

它的作用是获取匹配元素相对滚动条顶部的偏移。(此方法对可见和隐藏元素均有效)

用法:

比如设置相对滚动条顶部的偏移:$("div.demo").scrollTop(300);

在html和css代码中也需要注意定位反回顶部按钮的位置和使他浮在现有元素之上。

html代码:

 <div class="to_top" style="z-index:99999;display:block;">
</div>

css代码:

 /*这里是返回顶部按钮*/
.to_top {
position:fixed;
display:block;
background: url(../../images/footer-totop.png) no-repeat;
filter:alpha(opacity=50);
-moz-opacity:0.5;
opacity:0.5;
float:right;
width:60px;
height:60px;
margin-top:37%;
margin-left:95%;
}