u-sticky.vue 7.2 KB

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