简洁js滚动返回顶部按钮代码

简洁实用的代码,实现我们需要的功能。

这段代码超出首屏范围后,才出现返回顶部的按钮,点击按钮滚动返回顶部。这段代码非常简单实用,容易修改返回按钮图片样式。直接将这段下面插入需要返回顶部的页面中即可。

 
 
<!--返回顶部按钮-->
 
<style>
<!--样式在这里设置-->
#goTopBtn { 
position: fixed; text-align: center; line-height: 30px; width: 30px; bottom: 35px; height: 33px; font-size: 12px; cursor: pointer; right: 10px; _position: absolute; _right: auto 
} 
</style>
 
 
<!--返回顶部这四个字也可以用图片来替代-->
 
<div style="display: none" id="goTopBtn">返回顶部</div>
 
 
 
<script type="text/javascript"> 
function goTopEx() { 
var obj = document.getElementById("goTopBtn"); 
function getScrollTop() { 
return document.documentElement.scrollTop + document.body.scrollTop; 
} 
function setScrollTop(value) { 
if (document.documentElement.scrollTop) { 
document.documentElement.scrollTop = value; 
} else { 
document.body.scrollTop = value; 
} 
} 
window.onscroll = function() { 
getScrollTop() > 0 ? obj.style.display = "": obj.style.display = "none"; 
} 
obj.onclick = function() { 
var goTop = setInterval(scrollMove, 10); 
function scrollMove() { 
setScrollTop(getScrollTop() / 1.1); 
if (getScrollTop() < 1) clearInterval(goTop); } } } 
goTopEx();
</script> 
 
<!--返回顶部按钮-->
Leave a Reply

Your email address will not be published. Required fields are marked *