lj-sticky.vue 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <template>
  2. <nav style="width: 100%" :class="scrollFixed? 'isFixed' :''" :style="{top:scrollFixed? (offset+'px'):0}">
  3. <slot></slot>
  4. </nav>
  5. </template>
  6. <script>
  7. export default {
  8. name: "lj-sticky",
  9. props: {
  10. offset: {
  11. type: Number,
  12. default: 0
  13. }
  14. },
  15. data() {
  16. return {
  17. scrollFixed: false,
  18. offsetTop: 0
  19. }
  20. },
  21. methods: {
  22. windowScroll() {
  23. // 滚动条顶部 距 滚动原点的高度
  24. let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  25. /**
  26. * 两个高度比较
  27. * 如果滑动距离 > 吸顶元素到页面顶端距离 动态添加
  28. * scrollTop === 0时,页面回到顶部
  29. */
  30. let newFixed = scrollTop >= this.offsetTop && scrollTop > 0;
  31. if (this.scrollFixed !== newFixed) {
  32. this.scrollFixed = newFixed;
  33. if (newFixed) {
  34. this.$emit("sticky-on");
  35. } else {
  36. this.$emit("sticky-off");
  37. }
  38. }
  39. }
  40. },
  41. mounted() {
  42. // 需吸顶元素 距 离浏览器顶端的高度
  43. this.offsetTop = this.$el.offsetTop;
  44. // 滚动监听
  45. window.addEventListener('scroll', this.windowScroll);
  46. },
  47. destroyed() {
  48. // 关闭 销毁监听
  49. window.removeEventListener('scroll', this.windowScroll);
  50. }
  51. }
  52. </script>
  53. <style scoped>
  54. .isFixed {
  55. position: fixed;
  56. /*left: 0;*/
  57. z-index: 999;
  58. /*background: #12d168;*/
  59. transition: all 0.2s;
  60. /*color: #7511ff;*/
  61. }
  62. </style>