js实现回到顶部效果

本文介绍了如何使用JavaScript实现一个简单的页面回到顶部的效果。通过HTML创建返回顶部的按钮,CSS进行样式设置,JavaScript则用于监听按钮点击事件并实现页面滚动到顶部的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html:

<ul>                      //撑页面
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>
<a href="javascript:;" id="btn"><p>回到顶部</p></a>  //回到顶部按钮

css:

body,ul,li,p{
    margin: 0;
    padding: 0;
}
ul{
    list-style: none;
    width: 600px;
    margin: 0 auto;
}
li{
    width: 600px;
    height: 300px;
    text-align: center;
    line-height: 300px;
    font-size: 80px;
}
#btn{
    width: 40px;
    height: 40px;
    position: fixed;    //注意定位的位置
    left: 50%;
    margin-left: 330px;
    bottom: 30px;
    background: #ccc;
    text-decoration: none;
    color: #333333;
    font-size: 14px;
    text-align: center;
    display: table;
    display: none;
}
#btn:hover{
    background: orchid;
    color: #FFFFFF;
}
#btn p{
    display: table-cell;    //多行文字的垂直居中效果
    vertical-align: middle;
}

js:

var oBtn=document.getElementById("btn");
//获取页面可视区域的高度
var clientHeight=document.documentElement.clientHeight;
var timer=null;
var isTop=true;

window.onscroll=function(){
    var osTop=document.documentElement.scrollTop || document.body.scrollTop;
    if (osTop>=clientHeight) {  //回到顶部按钮在页面滚动到第二屏时出现
        oBtn.style.display='table';
    }else{
        oBtn.style.display='none';
    }

    if (!isTop) {  //在回到顶部的过程中,可随时阻止回到顶部
        clearInterval(timer);
    }
    isTop=false;
}

oBtn.onclick=function(){
    timer=setInterval(function(){
        var osTop=document.documentElement.scrollTop || document.body.scrollTop;
        var iSpeed=Math.floor(-osTop/7);

        document.documentElement.scrollTop=document.body.scrollTop=osTop+iSpeed;

        isTop=true;

        if (osTop==0) {  //回到顶部后清除定时器
            clearInterval(timer);
        }
    },30)

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值