u-sticky.vue 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. <template>
  2. <view
  3. class="u-sticky"
  4. :style="[style]"
  5. >
  6. <view
  7. :id="elId"
  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, getDeviceInfo, 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. watch: {
  93. offsetTop(nval) {
  94. this.getStickyTop()
  95. }
  96. },
  97. methods: {
  98. init() {
  99. this.getStickyTop()
  100. // 判断使用的模式
  101. this.checkSupportCssSticky()
  102. // 如果不支持css sticky,则使用js方案,此方案性能比不上css方案
  103. if (!this.cssSticky) {
  104. !this.disabled && this.initObserveContent()
  105. }
  106. },
  107. initObserveContent() {
  108. // 获取吸顶内容的高度,用于在js吸顶模式时,给父元素一个填充高度,防止"塌陷"
  109. this.$uGetRect('#' + this.elId).then((res) => {
  110. this.height = res.height
  111. this.left = res.left
  112. this.width = res.width
  113. this.$nextTick(() => {
  114. this.observeContent()
  115. })
  116. })
  117. },
  118. observeContent() {
  119. // 先断掉之前的观察
  120. this.disconnectObserver('contentObserver')
  121. const contentObserver = uni.createIntersectionObserver(this,{
  122. // 检测的区间范围
  123. thresholds: [0.95, 0.98, 1]
  124. })
  125. // 到屏幕顶部的高度时触发
  126. contentObserver.relativeToViewport({
  127. top: -this.stickyTop
  128. })
  129. // 绑定观察的元素
  130. contentObserver.observe(`#${this.elId}`, res => {
  131. this.setFixed(res.boundingClientRect.top)
  132. })
  133. this.contentObserver = contentObserver
  134. },
  135. setFixed(top) {
  136. // 判断是否出于吸顶条件范围
  137. const fixed = top <= this.stickyTop
  138. this.fixed = fixed
  139. },
  140. disconnectObserver(observerName) {
  141. // 断掉观察,释放资源
  142. const observer = this[observerName]
  143. observer && observer.disconnect()
  144. },
  145. getStickyTop() {
  146. this.stickyTop = getPx(this.offsetTop) + getPx(this.customNavHeight)
  147. },
  148. async checkSupportCssSticky() {
  149. // #ifdef H5
  150. // H5,一般都是现代浏览器,是支持css sticky的,这里使用创建元素嗅探的形式判断
  151. if (this.checkCssStickyForH5()) {
  152. this.cssSticky = true
  153. }
  154. // #endif
  155. // 如果安卓版本高于8.0,依然认为是支持css sticky的(因为安卓7在某些机型,可能不支持sticky)
  156. if (os() === 'android' && Number(getDeviceInfo().system) > 8) {
  157. this.cssSticky = true
  158. }
  159. // APP-Vue和微信平台,通过computedStyle判断是否支持css sticky
  160. // #ifdef APP-VUE || MP-WEIXIN || MP-TOUTIAO
  161. this.cssSticky = await this.checkComputedStyle()
  162. // #endif
  163. // ios上,从ios6开始,都是支持css sticky的
  164. if (os() === 'ios') {
  165. this.cssSticky = true
  166. }
  167. // nvue,是支持css sticky的
  168. // #ifdef APP-NVUE
  169. this.cssSticky = true
  170. // #endif
  171. },
  172. // 在APP和微信小程序上,通过uni.createSelectorQuery可以判断是否支持css sticky
  173. checkComputedStyle() {
  174. // 方法内进行判断,避免在其他平台生成无用代码
  175. // #ifdef APP-VUE || MP-WEIXIN || MP-TOUTIAO
  176. return new Promise(resolve => {
  177. uni.createSelectorQuery().in(this).select('.u-sticky').fields({
  178. computedStyle: ["position"]
  179. }).exec(e => {
  180. resolve('sticky' === e[0].position)
  181. })
  182. })
  183. // #endif
  184. },
  185. // H5通过创建元素的形式嗅探是否支持css sticky
  186. // 判断浏览器是否支持sticky属性
  187. checkCssStickyForH5() {
  188. // 方法内进行判断,避免在其他平台生成无用代码
  189. // #ifdef H5
  190. const vendorList = ['', '-webkit-', '-ms-', '-moz-', '-o-'],
  191. vendorListLength = vendorList.length,
  192. stickyElement = document.createElement('div')
  193. for (let i = 0; i < vendorListLength; i++) {
  194. stickyElement.style.position = vendorList[i] + 'sticky'
  195. if (stickyElement.style.position !== '') {
  196. return true
  197. }
  198. }
  199. return false;
  200. // #endif
  201. }
  202. },
  203. beforeUnmount() {
  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>