脚本宝典收集整理的这篇文章主要介绍了js实例教程-JavaScript实现回到顶部功能,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。
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) }
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技巧 脚本宝典 欢迎评论哦! js技巧,巧夺天工,精雕玉琢。小宝典献丑了!
以上是脚本宝典为你收集整理的js实例教程-JavaScript实现回到顶部功能全部内容,希望文章能够帮你解决js实例教程-JavaScript实现回到顶部功能所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。