u-sticky.vue 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. <template>
  2. <view
  3. class="u-sticky"
  4. :id="elId"
  5. :style="[style]"
  6. >
  7. <view
  8. :style="[stickyContent]"
  9. class="u-sticky__content"
  10. >
  11. <slot />
  12. </view>
  13. </view>
  14. </template>
  15. <script>
  16. import props from './props.js';
  17. import mixin from '../../libs/mixin/mixin'
  18. import mpMixin from '../../libs/mixin/mpMixin';;
  19. /**
  20. * sticky 吸顶
  21. * @description 该组件与CSS中position: sticky属性实现的效果一致,当组件达到预设的到顶部距离时, 就会固定在指定位置,组件位置大于预设的顶部距离时,会重新按照正常的布局排列。
  22. * @tutorial https://uview.d3u.cn/components/sticky.html
  23. * @property {String | Number} offsetTop 吸顶时与顶部的距离,单位px(默认 0 )
  24. * @property {String | Number} customNavHeight 自定义导航栏的高度 (h5 默认44 其他默认 0 )
  25. * @property {Boolean} disabled 是否开启吸顶功能 (默认 false )
  26. * @property {String} bgColor 组件背景颜色(默认 '#ffffff' )
  27. * @property {String | Number} zIndex 吸顶时的z-index值
  28. * @property {String | Number} index 自定义标识,用于区分是哪一个组件
  29. * @property {Object} customStyle 组件的样式,对象形式
  30. * @event {Function} fixed 组件吸顶时触发
  31. * @event {Function} unfixed 组件取消吸顶时触发
  32. * @example <u-sticky offsetTop="200"><view>塞下秋来风景异,衡阳雁去无留意</view></u-sticky>
  33. */
  34. export default {
  35. name: 'u-sticky',
  36. mixins: [mpMixin, mixin, props],
  37. data() {
  38. return {
  39. cssSticky: false, // 是否使用css的sticky实现
  40. stickyTop: 0, // 吸顶的top值,因为可能受自定义导航栏影响,最终的吸顶值非offsetTop值
  41. elId: uni.$u.guid(),
  42. left: 0, // js模式时,吸顶的内容因为处于postition: fixed模式,为了和原来保持一致的样式,需要记录并重新设置它的left,height,width属性
  43. width: 'auto',
  44. height: 'auto',
  45. fixed: false, // js模式时,是否处于吸顶模式
  46. }
  47. },
  48. computed: {
  49. style() {
  50. const style = {}
  51. if(!this.disabled) {
  52. if (this.cssSticky) {
  53. style.position = 'sticky'
  54. style.zIndex = this.zIndex
  55. style.top = uni.$u.addUnit(this.stickyTop)
  56. } else {
  57. style.height = this.fixed ? this.height + 'px' : 'auto'
  58. }
  59. } else {
  60. // 无需吸顶时,设置会默认的relative(nvue)和非nvue的static静态模式即可
  61. // #ifdef APP-NVUE
  62. style.position = 'relative'
  63. // #endif
  64. // #ifndef APP-NVUE
  65. style.position = 'static'
  66. // #endif
  67. }
  68. style.backgroundColor = this.bgColor
  69. return uni.$u.deepMerge(uni.$u.addStyle(this.customStyle), style)
  70. },
  71. // 吸顶内容的样式
  72. stickyContent() {
  73. const style = {}
  74. if (!this.cssSticky) {
  75. style.position = this.fixed ? 'fixed' : 'static'
  76. style.top = this.stickyTop + 'px'
  77. style.left = this.left + 'px'
  78. style.width = this.width == 'auto' ? 'auto' : this.width + 'px'
  79. style.zIndex = this.zIndex
  80. }
  81. return style
  82. }
  83. },
  84. mounted() {
  85. this.init()
  86. },
  87. methods: {
  88. init() {
  89. this.getStickyTop()
  90. // 判断使用的模式
  91. this.checkSupportCssSticky()
  92. // 如果不支持css sticky,则使用js方案,此方案性能比不上css方案
  93. if (!this.cssSticky) {
  94. !this.disabled && this.initObserveContent()
  95. }
  96. },
  97. initObserveContent() {
  98. // 获取吸顶内容的高度,用于在js吸顶模式时,给父元素一个填充高度,防止"塌陷"
  99. this.$uGetRect('#' + this.elId).then((res) => {
  100. this.height = res.height
  101. this.left = res.left
  102. this.width = res.width
  103. this.$nextTick(() => {
  104. this.observeContent()
  105. })
  106. })
  107. },
  108. observeContent() {
  109. // 先断掉之前的观察
  110. this.disconnectObserver('contentObserver')
  111. const contentObserver = uni.createIntersectionObserver({
  112. // 检测的区间范围
  113. thresholds: [0.95, 0.98, 1]
  114. })
  115. // 到屏幕顶部的高度时触发
  116. contentObserver.relativeToViewport({
  117. top: -this.stickyTop
  118. })
  119. // 绑定观察的元素
  120. contentObserver.observe(`#${this.elId}`, res => {
  121. this.setFixed(res.boundingClientRect.top)
  122. })
  123. this.contentObserver = contentObserver
  124. },
  125. setFixed(top) {
  126. // 判断是否出于吸顶条件范围
  127. const fixed = top <= this.stickyTop
  128. this.fixed = fixed
  129. },
  130. disconnectObserver(observerName) {
  131. // 断掉观察,释放资源
  132. const observer = this[observerName]
  133. observer && observer.disconnect()
  134. },
  135. getStickyTop() {
  136. this.stickyTop = uni.$u.getPx(this.offsetTop) + uni.$u.getPx(this.customNavHeight)
  137. },
  138. async checkSupportCssSticky() {
  139. // #ifdef H5
  140. // H5,一般都是现代浏览器,是支持css sticky的,这里使用创建元素嗅探的形式判断
  141. if (this.checkCssStickyForH5()) {
  142. this.cssSticky = true
  143. }
  144. // #endif
  145. // 如果安卓版本高于8.0,依然认为是支持css sticky的(因为安卓7在某些机型,可能不支持sticky)
  146. // #ifdef APP-PLUS
  147. if (uni.$u.os() === 'android' && Number(uni.$u.sys().system) > 8) {
  148. this.cssSticky = true
  149. }
  150. // #endif
  151. // APP-Vue和微信平台,通过computedStyle判断是否支持css sticky
  152. // #ifdef APP-VUE || MP-WEIXIN
  153. this.cssSticky = await this.checkComputedStyle()
  154. // #endif
  155. // ios上,从ios6开始,都是支持css sticky的
  156. if (uni.$u.os() === 'ios') {
  157. this.cssSticky = true
  158. }
  159. // nvue,是支持css sticky的
  160. // #ifdef APP-NVUE
  161. this.cssSticky = true
  162. // #endif
  163. },
  164. // 在APP和微信小程序上,通过uni.createSelectorQuery可以判断是否支持css sticky
  165. checkComputedStyle() {
  166. // 方法内进行判断,避免在其他平台生成无用代码
  167. // #ifdef APP-VUE || MP-WEIXIN
  168. return new Promise(resolve => {
  169. uni.createSelectorQuery().in(this).select('.u-sticky').fields({
  170. computedStyle: ["position"]
  171. }).exec(e => {
  172. resolve('sticky' === e[0].position)
  173. })
  174. })
  175. // #endif
  176. },
  177. // H5通过创建元素的形式嗅探是否支持css sticky
  178. // 判断浏览器是否支持sticky属性
  179. checkCssStickyForH5() {
  180. // 方法内进行判断,避免在其他平台生成无用代码
  181. // #ifdef H5
  182. const vendorList = ['', '-webkit-', '-ms-', '-moz-', '-o-'],
  183. vendorListLength = vendorList.length,
  184. stickyElement = document.createElement('div')
  185. for (let i = 0; i < vendorListLength; i++) {
  186. stickyElement.style.position = vendorList[i] + 'sticky'
  187. if (stickyElement.style.position !== '') {
  188. return true
  189. }
  190. }
  191. return false;
  192. // #endif
  193. }
  194. },
  195. // #ifdef VUE2
  196. beforeDestroy() {
  197. this.disconnectObserver('contentObserver')
  198. }
  199. // #endif
  200. // #ifdef VUE3
  201. beforeUnmount() {
  202. this.disconnectObserver('contentObserver')
  203. }
  204. // #endif
  205. }
  206. </script>
  207. <style lang="scss" scoped>
  208. .u-sticky {
  209. /* #ifdef APP-VUE || MP-WEIXIN */
  210. // 此处默认写sticky属性,是为了给微信和APP通过uni.createSelectorQuery查询是否支持css sticky使用
  211. position: sticky;
  212. /* #endif */
  213. }
  214. </style>