回到顶部练习
<!DOCTYPE html> <html>
<head> <meta charset="UTF-8"> <title>回到顶部</title> <style> #to_top { width: 30px; height: 40px; font: 14px/20px arial; text-align: center; background: #06c; position: fixed; cursor: pointer; color: #fff; left: 1050px; top: 500px; } </style> </head> <body style="height: 2000px;">
<div id="to_top">返回顶部</div>
<script type="text/javascript" src="jquery-1.10.1.js"></script> <script type="text/javascript"> var $topBox = $('#to_top') $topBox.click(function(){ var $page = $('html,body') var $distance = $('html').scrollTop() + $('body').scrollTop() var time = 400 var $distanceTime = 30 var $itemDistance = $distance / (time / $distanceTime) var intervalId = setInterval(function(){ $distance -= $itemDistance if($distance <= 0){ $distance = 0 clearInterval(intervalId) } $page.scrollTop($distance) },$distanceTime) }) </script> </body>
</html>
|
总结
间隔时间可以根据自身进行修改,以达到一个看上去更加柔顺的一个平滑过渡