当页面过长时,通常会在页面下方有一个返回顶部的button,总结一下,大概三种实现方法,下面说下各方法及优缺点。

方法一 锚点定位

?
1
<a href="#" class="top" id="top">返回頂部</a>

这种方法设置方便,但缺点是会刷新页面(我是在同事的乐视手机上发现的)。

方法二 window.scrollTo(x,y)

?
1
<a href="javascript:scrollTo(0,0)" class="top" id="top">返回頂部</a>

这种方法也很方便,并且不会刷新页面,缺点是没有滚动效果。

scrollTo接收的参数用来定位视口左上角在整个滚动内容区域的坐标,比如我设置scrollTo(100,100),就是让滚动内容的坐标(100,100)的点处在视口的左上角。

方法三 jQuery插件设置带有动画效果的滚动

原生方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* html部分 */
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<a href="javascript:;" class="top" id="top">返回頂部</a>
</body>
<style>
/* css部分 */
div {
  height: 150px;
}
div:nth-child(odd) {
   padding: 0px 0px 0px 5px; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; border-left: 3px solid rgb(108, 226, 108); line-height: 20px; width: 640px; clear: both; outline: 0px !important; border-radius: 0px !important; border-top: 0px !important; border-right: 0px !important; border-bottom: 0px !important; border-image: initial !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; overflow: visible !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; box-sizing: content-box !important; font-family: Consolas, "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; min-height: auto !important; color: gray !important;">#8ae238;
}
div:nth-child(even) {
   padding: 0px 0px 0px 5px; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; border-left: 3px solid rgb(108, 226, 108); line-height: 20px; width: 640px; clear: both; outline: 0px !important; border-radius: 0px !important; border-top: 0px !important; border-right: 0px !important; border-bottom: 0px !important; border-image: initial !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; overflow: visible !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; box-sizing: content-box !important; font-family: Consolas, "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; min-height: auto !important; color: gray !important;">#66d9ef;
}
.top {
  position: fixed;
  right: 50px;
  bottom: 50px;
  display: block;
  width: 50px;
  height: 50px;
  font-size: 20px;
  
  display: none;
}
</style>
<script>
/* js代码 */
  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);
  }
</script>

大概的思路就是:

为window绑定scroll事件,监听页面滚动距离,当超过一屏高度时,显示返回顶部的按钮

为按钮绑定点击事件,返回顶部的方法就是获取页面滚动的距离,然后计算步长,这里采用滚动距离除以5的方式,滚动速度由快到慢。这里使用js定时器控制滚动的频率,建议设置较小一点的值,如果时间间隔过大会有‘跳帧'的感觉。
这种方法优点是有了动画效果,只是实现起来比较麻烦,下面介绍一下jQuery方法。

jQuery特效方法

jQuery方法只是在js代码部分不同,具体代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
/* js代码 */
$(window).on('scroll', function () {
  // 判断显示还是隐藏按钮
  if($(this).scrollTop()>=$(this).height()){
    $('#top').fadeIn('slow');
  }else {
    $('#top').fadeOut('slow');
  }
});
$('#top').on('click',function () {
  // 设置滚动动画,这里注意使用的是$('body')不是$(window)
  $('body').animate({scrollTop:'0'},500);
});
</script>

jQuery方法的优点是方便,而且动画效果比较流畅。

这里需要注意设置animate方法时使用的是jQuery封装的body对象而不是window对象,因为我们是要设置body的scrollTop属性。

总结

三个方法各有优劣,不过总体来讲,jQuery的方法更适合大多数场景。

jQuery中页面返回顶部的方法总结的更多相关文章

  1. 关于 ionic3 tabs 导航ico 点击 页面返回顶部

    类似微信 双击 页面返回顶部功能,ionic3 中有一个 Content. 将 import { Content } from 'ionic-angular'; 放入想要实现此功能的 ts中. 实例化 ...

  2. JQuery中操作Css样式的方法

    JQuery中操作Css样式的方法//1.获取和设置样式 $("#tow").attr("class")获取ID为tow的class属性 $("#tw ...

  3. 浅析jQuery中常用的元素查找方法总结

    本篇文章是对jQuery中常用的元素查找方法进行了详细的总结和介绍,需要的朋友参考下   $("#myELement") 选择id值等于myElement的元素,id值不能重复在文 ...

  4. 【转发】JQuery中操作Css样式的方法

    JQuery中操作Css样式的方法 //1.获取和设置样式 $("#tow").attr("class")获取ID为tow的class属性 $("#t ...

  5. jquery中prop()方法和attr()方法

    接着上一篇笔记的疑惑,找了下prop()方法和attr()方法的区别. 原来query1.6中新加了一个方法prop(),一直没用过它,官方解释只有一句话:获取在匹配的元素集中的第一个元素的属性值. ...

  6. js进阶 10-3 jquery中为什么用document.ready方法

    js进阶 10-3  jquery中为什么用document.ready方法 一.总结 一句话总结: 1.document.ready和window.onload的区别:用哪个好? document. ...

  7. 使用jQuery简单实现返回顶部的一个小案例

    1.简单写一个页面 首先我们应该创建两个盒子,container盒子主要模拟页面滚动到的位置,back盒子主要功能是实现返回顶部的功能 2.简单的对这两个盒子写一些样式 我们应该先将返回顶部盒子隐藏( ...

  8. jQuery火箭图标返回顶部代码

    在网上找来段使用jQuery火箭图标返回顶部代码,感觉比较酷,比较炫,大概样式如下, 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. ...

  9. js进阶 12-13 jquery中one方法和trigger方法如何使用

    js进阶 12-13 jquery中one方法和trigger方法如何使用 一.总结 一句话总结: 1.one()方法和on()方法的区别是什么? 除了one()只执行一次,其它和on()一模一样,包 ...

随机推荐

  1. JAVA编程思想的理解

    1)POP--面向过程编程(Process-oriented programming ):   面向过程编程是以功能为中心来进行思考和组织的一种编程方法,它强调的是系统的数据被加工和处理的过程,在程序 ...

  2. Javascript高级编程学习笔记(79)—— 表单(7)选择框脚本

    选择框脚本 选择框由<option>和<select>元素创建,为了方便选择框的交互,除了提供表单字段的公有方法之外 HTMLSelectElement 类型还提供下列特有的属 ...

  3. 从零开始单排学设计模式「策略模式」黑铁 II

    阅读本文大概需要 1.7 分钟. 本篇是设计模式系列的第三篇,虽然之前也写过相应的文章,但是因为种种原因后来断掉了,而且发现之前写的内容也很渣,不够系统.所以现在打算重写,加上距离现在也有一段时间了, ...

  4. linux中修改字符编码

    一. ubuntu修改字符编码 1. 添加字符编码,例如zh_CN.UTF-8,有两种方式 方法1:locale-gen zh_CN.UTF-8   #locale-gen命令只在ubuntu中才有 ...

  5. HC-06蓝牙模块的使用

    HC-06蓝牙模块与HC-05的AT指令变化还是挺大的,在模块上电后红灯闪烁表示未连接成功,常亮表示连接成功,期间只要红灯处于闪烁即是进入了AT模式,可发送AT指令,灯常亮使用AT指令无效.下面是常用 ...

  6. 【新手向】使用nodejs抓取百度贴吧内容

    参考教程:https://github.com/alsotang/node-lessons 1~5节 1. 通过superagent抓取页面内容 superagent .get('http://www ...

  7. mysql 架构篇系列 2 复制架构一主一从搭建(异步复制)

    一. 环境准备 1.1 主库环境(172.168.18.201) 环境 说明 查看脚本 操作系统版本 CentOS Linux release 7.4.1708 (Core) cat /etc/red ...

  8. Execution failed for task ':app:processDebugResources'

    经常会遇到突然AndroidStudio编译不了程序,报错误: Execution failed for task ':app:processDebugResources'. > Failed ...

  9. Chapter 4 Invitations——4

    I wanted very much to talk to him, and the day after the accident I tried. 在发生事故之后我尽力尝试,我很想和他聊聊. The ...

  10. 【原创】深入理解c++的右值引用

    0 左值和右值     一个左值表达式代表的是对象本身,而右值表达式代表的是对象的值:变量也是左值.   1 右值引用作用 为了支持移动操作(包括移动构造函数和移动赋值函数),C++才引入了一种新的引 ...