本文实例为大家分享了JS返回顶部实例代码,供大家参考,具体内容如下
html/css部分
Document.container{
width:1190px;
margin: 0px auto;
}
.container a{
display: none;
width:40px;
height:40px;
background: url(/535e0dc100010e9c00400080.jpg) no-repeat;
position: fixed;
left:95%;
bottom: 50px;
}
.container a:hover{
background: url(/535e0dc100010e9c00400080.jpg) no-repeat;
background-position: left -40px;
}
JS部分
window.onload=function(){
var obtn=document.getElementById("btn");
var clientHeight=document.documentElement.clientHeight||ocument.body.clientHeight;
var isTop=true;
var timer=null;
window.onscroll=function(){
var topH=document.documentElement.scrollTop||document.body.scrollTop;
if(topH>clientHeight){
obtn.style.display="block";
}else{
obtn.style.display="none";
}
}
obtn.onclick=function(){
timer=setInterval(function(){
var topH=document.documentElement.scrollTop||document.body.scrollTop;
var stepLength=Math.ceil(topH/5);
document.documentElement.scrollTop=document.body.scrollTop=topH-stepLength;
if(topH==0){
clearInterval(timer);
}
},30);
}
}
学习视频地址
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
本文详细介绍了如何使用JavaScript实现网页返回顶部的功能。通过监听滚动事件,当页面滚动到一定位置时显示返回顶部按钮,点击按钮则平滑滚动回页面顶部。代码包括HTML、CSS和JS部分,适合前端开发者学习参考。


2216

被折叠的 条评论
为什么被折叠?



