3
0

u-sticky.vue 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. offsetTop(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. console.log('this.offsetTop',this.offsetTop);
  142. this.stickyTop = getPx(this.offsetTop) + getPx(this.customNavHeight)
  143. },
  144. async checkSupportCssSticky() {
  145. // #ifdef H5
  146. // H5,一般都是现代浏览器,是支持css sticky的,这里使用创建元素嗅探的形式判断
  147. if (this.checkCssStickyForH5()) {
  148. this.cssSticky = true
  149. }
  150. // #endif
  151. // 如果安卓版本高于8.0,依然认为是支持css sticky的(因为安卓7在某些机型,可能不支持sticky)
  152. if (os() === 'android' && Number(sys().system) > 8) {
  153. this.cssSticky = true
  154. }
  155. // APP-Vue和微信平台,通过computedStyle判断是否支持css sticky
  156. // #ifdef APP-VUE || MP-WEIXIN || MP-TOUTIAO
  157. this.cssSticky = await this.checkComputedStyle()
  158. // #endif
  159. // ios上,从ios6开始,都是支持css sticky的
  160. if (os() === 'ios') {
  161. this.cssSticky = true
  162. }
  163. // nvue,是支持css sticky的
  164. // #ifdef APP-NVUE
  165. this.cssSticky = true
  166. // #endif
  167. },
  168. // 在APP和微信小程序上,通过uni.createSelectorQuery可以判断是否支持css sticky
  169. checkComputedStyle() {
  170. // 方法内进行判断,避免在其他平台生成无用代码
  171. // #ifdef APP-VUE || MP-WEIXIN || MP-TOUTIAO
  172. return new Promise(resolve => {
  173. uni.createSelectorQuery().in(this).select('.u-sticky').fields({
  174. computedStyle: ["position"]
  175. }).exec(e => {
  176. resolve('sticky' === e[0].position)
  177. })
  178. })
  179. // #endif
  180. },
  181. // H5通过创建元素的形式嗅探是否支持css sticky
  182. // 判断浏览器是否支持sticky属性
  183. checkCssStickyForH5() {
  184. // 方法内进行判断,避免在其他平台生成无用代码
  185. // #ifdef H5
  186. const vendorList = ['', '-webkit-', '-ms-', '-moz-', '-o-'],
  187. vendorListLength = vendorList.length,
  188. stickyElement = document.createElement('div')
  189. for (let i = 0; i < vendorListLength; i++) {
  190. stickyElement.style.position = vendorList[i] + 'sticky'
  191. if (stickyElement.style.position !== '') {
  192. return true
  193. }
  194. }
  195. return false;
  196. // #endif
  197. }
  198. },
  199. beforeUnmount() {
  200. this.disconnectObserver('contentObserver')
  201. }
  202. }
  203. </script>
  204. <style lang="scss" scoped>
  205. .u-sticky {
  206. /* #ifdef APP-VUE || MP-WEIXIN || MP-TOUTIAO */
  207. // 此处默认写sticky属性,是为了给微信和APP通过uni.createSelectorQuery查询是否支持css sticky使用
  208. position: sticky;
  209. /* #endif */
  210. }
  211. </style>