jquery回到顶部代码

HTML代码:

<div class="return"><a id="mtop_div" class="return_top"></a></div>

css代码:

.return {
position: fixed;
right: 0.5rem;
bottom: 1rem;
z-index: 99999;
height: 7.5rem;
}
.return .return_top {
width: 3.5rem;
height: 3.5rem;
cursor: pointer;
background: url(totop.png) no-repeat;
background-size: 3.5rem;
display: block;
font-size: 0rem;
}

代码1(有时候会冲突):

$(function(){$(function () {$(window).scroll(function(){if ($(window).scrollTop()>500){$("#mtop_div").fadeIn(500);}else{$("#mtop_div").fadeOut(500);}});});});
if (top.location != self.location)top.location=self.location;

建议使用代码2:

$(document).ready(function() {
//首先将#mtop_div隐藏
$("#mtop_div").hide();
//当滚动条的位置处于距顶部50像素以下时,跳转链接出现,否则消失
$(function() {
$(window).scroll(function() {
if ($(window).scrollTop() > 50) {
$("#mtop_div").fadeIn(200);
} else {
$("#mtop_div").fadeOut(200);
}
});
//当点击跳转链接后,回到页面顶部位置
$("#mtop_div").click(function() {
$('body,html').animate({
scrollTop: 0
},
500);
return false;
});
});
});
原文地址:https://www.cnblogs.com/xinlvtian/p/13181033.html