You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

221 lines
7.1 KiB

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