sidebar.vue 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <template>
  2. <div class="client-sidebar">
  3. <ul>
  4. <li><a><i></i></a></li>
  5. <li><i @click="backTop"></i></li>
  6. </ul>
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. name: 'mtaSidebar',
  12. // vue的两个生命钩子,这里不多解释。
  13. // window对象,所有浏览器都支持window对象。它表示浏览器窗口,监听滚动事件
  14. mounted () {
  15. window.addEventListener('scroll', this.scrollToTop)
  16. },
  17. destroyed () {
  18. window.removeEventListener('scroll', this.scrollToTop)
  19. },
  20. methods: {
  21. // 点击图片回到顶部方法,加计时器是为了过渡顺滑
  22. backTop() {
  23. const that = this
  24. let timer = setInterval(() => {
  25. let ispeed = Math.floor(-that.scrollTop / 5)
  26. document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
  27. if (that.scrollTop === 0) {
  28. clearInterval(timer)
  29. }
  30. }, 16)
  31. },
  32. // 为了计算距离顶部的高度,当高度大于60显示回顶部图标,小于60则隐藏
  33. scrollToTop() {
  34. const that = this
  35. let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  36. that.scrollTop = scrollTop
  37. if (that.scrollTop > 60) {
  38. that.btnFlag = true
  39. } else {
  40. that.btnFlag = false
  41. }
  42. }
  43. }
  44. };
  45. </script>
  46. <style lang="scss" scoped>
  47. .client-sidebar{
  48. display: none;
  49. position: fixed;
  50. z-index: 100;
  51. top: 220px;
  52. right: 0;
  53. i{width: 50px;height: 50px;display: block;}
  54. li:nth-child(1) i{background: pink;}
  55. li:nth-child(2) i{background: green;}
  56. }
  57. </style>