整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

html中如何写“返回顶部按钮”?

var topBtn = document.getElementById('top');
// 获取视窗高度
var winHeight = document.documentElement.clientHeight;
window.onscroll = function () {
    // 获取页面向上滚动距离,chrome浏览器识别document.body.scrollTop,而火狐识别document.documentElement.scrollTop,这里做了兼容处理
    var toTop = document.documentElement.scrollTop || document.body.scrollTop;
    // 如果滚动超过一屏,返回顶部按钮出现,反之隐藏
    if(toTop>=winHeight){
        topBtn.style.display = 'block';
    }else {
        topBtn.style.display = 'none';
    }
}
topBtn.onclick=function () {
    var timer = setInterval(function () {
        var toTop = document.documentElement.scrollTop || document.body.scrollTop;
        // 判断是否到达顶部,到达顶部停止滚动,没到达顶部继续滚动
        if(toTop == 0){
            clearInterval(timer);
        }else {
            // 设置滚动速度
            var speed = Math.ceil(toTop/5);
            // 页面向上滚动
            document.documentElement.scrollTop=document.body.scrollTop=toTop-speed;
        }
    },50);
}

大家介绍如何通过 JS/CSS 实现网页返回顶部效果。

CSS 按钮样式:

#myBtn {

display: none; /* 默认隐藏 */

position: fixed;

bottom: 20px;

right: 30px;

z-index: 99;

border: none;

outline: none;

background-color: red; /* 设置背景颜色,你可以设置自己想要的颜色或图片 */

color: white; /* 文本颜色 */

cursor: pointer;

padding: 15px;

border-radius: 10px; /* 圆角 */

}