index.ts 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { getStatusBarHeight } from '../../stores/index'
  2. Component({
  3. externalClasses: ['custom-class'],
  4. options: {
  5. multipleSlots: true, // 在组件定义时的选项中启用多slot支持
  6. },
  7. properties: {
  8. // 是否显示返回按钮
  9. showBackButton: {
  10. type: Boolean,
  11. value: false,
  12. },
  13. // 是否固定导航栏
  14. navBarFixed: {
  15. type: Boolean,
  16. value: false,
  17. },
  18. // 导航栏固定时状态栏颜色
  19. statusBarFixedStyle: {
  20. type: Object,
  21. value: <WechatMiniprogram.SetNavigationBarColorOption>{
  22. frontColor: '#000000',
  23. backgroundColor: '#ffffff',
  24. },
  25. },
  26. // 页面滚动时状态栏颜色
  27. statusBarScrollStyle: {
  28. type: Object,
  29. value: <WechatMiniprogram.SetNavigationBarColorOption>{
  30. frontColor: '#ffffff',
  31. backgroundColor: '#fd4c58',
  32. },
  33. }
  34. },
  35. data: {
  36. backButtonOpacity: 1, // 返回按钮透明度,(scrollHeight - scrollTop) / scrollHeight
  37. navBarOpacity: 0, // 导航栏透明度
  38. statusBarHeight: getStatusBarHeight(),
  39. },
  40. methods: {
  41. // 设置状态栏颜色
  42. setStatusBarStyle(option: Object) {
  43. const style = option as WechatMiniprogram.SetNavigationBarColorOption
  44. wx.setNavigationBarColor(style)
  45. },
  46. // 监听滚动条滚动事件
  47. onScroll(e: any) {
  48. if (this.data.navBarFixed) {
  49. const scrollTop = e.detail.scrollTop
  50. const scrollHeight = 100 // 最大滚动高度
  51. const statusBarHeight = this.data.statusBarHeight
  52. const navBarOpacity = (scrollTop - statusBarHeight) / scrollHeight // 计算透明度
  53. // 待优化
  54. // if (navBarOpacity < 1.5) {
  55. // this.setData({
  56. // navBarOpacity,
  57. // }, () => {
  58. // if (navBarOpacity > 0.5) {
  59. // this.setStatusBarStyle(this.data.statusBarScrollStyle)
  60. // } else {
  61. // this.setStatusBarStyle(this.data.statusBarFixedStyle)
  62. // }
  63. // })
  64. // }
  65. // 暂时解决方案
  66. if (this.data.navBarOpacity === 0 && navBarOpacity > 1) {
  67. this.setData({
  68. navBarOpacity: 1,
  69. }, () => {
  70. this.setStatusBarStyle(this.data.statusBarScrollStyle)
  71. })
  72. } else if (this.data.navBarOpacity === 1 && navBarOpacity < 1) {
  73. this.setData({
  74. navBarOpacity: 0,
  75. }, () => {
  76. this.setStatusBarStyle(this.data.statusBarFixedStyle)
  77. })
  78. }
  79. }
  80. }
  81. },
  82. attached() {
  83. if (this.data.navBarFixed) {
  84. this.setStatusBarStyle(this.data.statusBarFixedStyle)
  85. }
  86. }
  87. })