u-sticky.vue 7.2 KB

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