博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
js或jQuery实现返回顶部功能------Sestid
阅读量:4047 次
发布时间:2019-05-24

本文共 1809 字,大约阅读时间需要 6 分钟。

 

1、纯js,无动画版本

window.scrollTo(x-coord, y-coord);  window.scrollTo(0,0);

2、纯js,带动画版本

生硬版:

var scrollToTop = window.setInterval(function() {    var pos = window.pageYOffset;    if ( pos > 0 ) {        window.scrollTo( 0, pos - 20 ); // how far to scroll on each step    } else {        window.clearInterval( scrollToTop );    }}, 16); // how fast to scroll (this equals roughly 60 fps)

流畅版:

(function smoothscroll(){    var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;    if (currentScroll > 0) {         window.requestAnimationFrame(smoothscroll);         window.scrollTo (0,currentScroll - (currentScroll/5));    }})();

3、jQuery,带动画版本(包括html,css,js)

首先需要在顶部添加如下html元素:

    

返回顶部

其中a标签指向锚点top,可以在顶部防止一个<a name="top"></a>的锚点,这样在浏览器不支持js时也可以实现返回顶部的效果了。

要想让返回顶部的图片显示在右侧,还需要一些css样式,如下:

p#back-to-top{    position:fixed;    display:none;    bottom:100px;    right:80px;}p#back-to-top a{    text-align:center;    text-decoration:none;    color:#d1d1d1;    display:block;    width:64px;    /*使用CSS3中的transition属性给跳转链接中的文字添加渐变效果*/    -moz-transition:color 1s;    -webkit-transition:color 1s;    -o-transition:color 1s;}p#back-to-top a:hover{    color:#979797;}p#back-to-top a span{    background:transparent url(/static/imgs/sprite.png?1202) no-repeat -25px -290px;    border-radius:6px;    display:block;    height:64px;    width:56px;    margin-bottom:5px;    /*使用CSS3中的transition属性给标签背景颜色添加渐变效果*/    -moz-transition:background 1s;    -webkit-transition:background 1s;    -o-transition:background 1s;}#back-to-top a:hover span{    background:transparent url(/static/imgs/sprite.png?1202) no-repeat -25px -290px;}

上面样式中的背景图片是雪碧图,下面提供两个单独的返回顶部图片方便朋友们使用:

go-top-icon go-top-icon2go-top-light-green go-top-green go-top-yellow

有了html和样式,我们还需要用js控制返回顶部按钮,在页面滚动时渐隐渐现返回顶部按钮。

这样就可以了。

注意在载入页面后需要向下拖动一点滚动条才可以看到返回顶部的效果图。

转载地址:http://ewwci.baihongyu.com/

你可能感兴趣的文章
看看腾讯和百度等这样的大型网站系统架构是如何演化的
查看>>
AMQP与QPID简介
查看>>
nginx虚拟主机
查看>>
Nginx 性能调优
查看>>
nginx rewrite规则之last和break
查看>>
Redis和Memcached的区别
查看>>
Memcached 集群的高可用(HA)架构
查看>>
浏览器端的缓存规则
查看>>
redis持久化RDB和AOF
查看>>
Redis持久化存储(AOF与RDB两种模式)
查看>>
memcached工作原理与优化建议
查看>>
Redis与Memcached的区别
查看>>
redis sharding方案
查看>>
程序员最核心的竞争力是什么?
查看>>
阿里、网易、滴滴共十次前端面试碰到的问题
查看>>
memcache、redis原理对比
查看>>
Node.js机制及原理理解初步
查看>>
linux CPU个数查看
查看>>
linux系统负载load average的含义
查看>>
分布式应用开发相关的面试题收集
查看>>