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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
| <template>
| <div class="backTop" :style="{ right: right + 'px', bottom: bottom + 'px' }" v-if="showBackTop">
| <i class="iconfont icon-xsaaa" :style="{ fontSize: fontSize + 'px' }" @click="backTop"></i>
| </div>
| </template>
|
| <script>
| export default {
| name: 'BackTop',
| props: {
| right: {
| type: Number,
| default: 50,
| },
| bottom: {
| type: Number,
| default: 50,
| },
| fontSize: {
| type: Number,
| default: 18,
| },
| },
| data() {
| return {
| targetDom: null, // 当前滚动对象
| showBackTop: false, // 是否显示回到顶部标识
| scrollY: 0, // 滚动距离
| }
| },
| mounted() {
| // 监听页面滚动
| window.addEventListener('scroll', this.handleScroll, true)
| },
| methods: {
| handleScroll(e) {
| this.scrollY = e.target.scrollTop
| this.showBackTop = e.target.scrollTop > 100 // 页面滚动距离大于100的时候显示回到top的标识
| this.targetDom = e
| },
| // 滑动到顶部
| backTop() {
| const _this = this
| let timer = requestAnimationFrame(function fn() {
| const currentTop = _this.targetDom.target.scrollTop
| if (currentTop > 0) {
| // 平滑滚动
| const scrollSpeed = currentTop + (0 - currentTop) / 6
| _this.targetDom.target.scrollTop = scrollSpeed
| timer = requestAnimationFrame(fn)
| } else {
| cancelAnimationFrame(timer)
| }
| })
| },
| },
| unmounted() {
| window.removeEventListener('scroll', this.handleScroll)
| },
| }
| </script>
|
| <style lang="scss" scoped>
| .backTop {
| position: fixed;
| display: inline-block;
| text-align: center;
| cursor: pointer;
| width: 50px;
| height: 50px;
| border-radius: 4px;
| line-height: 50px;
| z-index: 3;
| color: $theme;
| opacity: 0.7;
| &:hover {
| opacity: 1;
| }
| }
| </style>
|
|