JavaScript实现回到顶部功能
程序员文章站
2022-05-07 21:25:42
html代码
css代码
* {
margin: 0;...
html代码
<p id="box"></p>
css代码
* { margin: 0; padding: 0; } body { height: 3000px; } #box { width: 100px; height: 100px; background: red; position: absolute; right: 0; }
JS代码
var oBox = document.getElementById("box"); var timer = null; var iH = document.documentElement.clientHeight; oBox.style.top = iH / 2 - oBox.offsetHeight / 2 + "px"; document.onscroll = function () { var iT = document.documentElement.scrollTop || document.body.scrollTop; var iTarget = Math.round(iH / 2) - Math.round(oBox.offsetHeight / 2) + iT; move(oBox, iTarget); }; function move(obj, iTarget) { clearInterval(timer); timer = setInterval(function () { var speed = (iTarget - obj.offsetTop) / 8; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if (obj.offsetTop == iTarget) { clearInterval(timer); } else { obj.style.top = obj.offsetTop + speed + 'px'; } }, 30) }
推荐阅读
-
用javascript实现的图片马赛克后显示并切换加文字功能
-
如何用JavaScript实现功能齐全的单链表详解
-
JavaScript实现经纬度转换成地址功能
-
javascript实现对话框功能警告(alert 消息对话框)确认(confirm 消息对话框)
-
javascript使用substring实现的展开与收缩文字功能示例
-
javascript实现的图片预览和上传功能示例【兼容IE 9】
-
CSS JavaScript 实现菜单功能 改进版
-
JavaScript实现的前端AES加密解密功能【基于CryptoJS】
-
JavaScript基于replace+正则实现ES6的字符串模版功能
-
用JavaScript实现页面重定向功能的教程