bug
jiangping
2023-11-07 64b432916af9c9218ab3f3eca614e26c542142ae
minipro_standard/uni_modules/uview-ui/components/u-sticky/u-sticky.vue
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,212 @@
<template>
   <view
      class="u-sticky"
      :id="elId"
      :style="[style]"
   >
      <view
         :style="[stickyContent]"
         class="u-sticky__content"
      >
         <slot />
      </view>
   </view>
</template>
<script>
   import props from './props.js';;
   /**
    * sticky å¸é¡¶
    * @description è¯¥ç»„件与CSS中position: sticky属性实现的效果一致,当组件达到预设的到顶部距离时, å°±ä¼šå›ºå®šåœ¨æŒ‡å®šä½ç½®ï¼Œç»„件位置大于预设的顶部距离时,会重新按照正常的布局排列。
    * @tutorial https://www.uviewui.com/components/sticky.html
    * @property {String ï½œ Number}   offsetTop      å¸é¡¶æ—¶ä¸Žé¡¶éƒ¨çš„距离,单位px(默认 0 ï¼‰
    * @property {String ï½œ Number}   customNavHeight   è‡ªå®šä¹‰å¯¼èˆªæ çš„高度 ï¼ˆh5 é»˜è®¤44  å…¶ä»–默认 0 ï¼‰
    * @property {Boolean}         disabled      æ˜¯å¦å¼€å¯å¸é¡¶åŠŸèƒ½ ï¼ˆé»˜è®¤ false ï¼‰
    * @property {String}         bgColor         ç»„件背景颜色(默认 '#ffffff' ï¼‰
    * @property {String ï½œ Number}   zIndex         å¸é¡¶æ—¶çš„z-index值
    * @property {String ï½œ Number}   index         è‡ªå®šä¹‰æ ‡è¯†ï¼Œç”¨äºŽåŒºåˆ†æ˜¯å“ªä¸€ä¸ªç»„ä»¶
    * @property {Object}         customStyle      ç»„件的样式,对象形式
    * @event {Function} fixed      ç»„件吸顶时触发
    * @event {Function} unfixed   ç»„件取消吸顶时触发
    * @example <u-sticky offsetTop="200"><view>塞下秋来风景异,衡阳雁去无留意</view></u-sticky>
    */
   export default {
      name: 'u-sticky',
      mixins: [uni.$u.mpMixin, uni.$u.mixin, props],
      data() {
         return {
            cssSticky: false, // æ˜¯å¦ä½¿ç”¨css的sticky实现
            stickyTop: 0, // å¸é¡¶çš„top值,因为可能受自定义导航栏影响,最终的吸顶值非offsetTop值
            elId: uni.$u.guid(),
            left: 0, // js模式时,吸顶的内容因为处于postition: fixed模式,为了和原来保持一致的样式,需要记录并重新设置它的left,height,width属性
            width: 'auto',
            height: 'auto',
            fixed: false, // js模式时,是否处于吸顶模式
         }
      },
      computed: {
         style() {
            const style = {}
            if(!this.disabled) {
               if (this.cssSticky) {
                  style.position = 'sticky'
                  style.zIndex = this.uZindex
                  style.top = uni.$u.addUnit(this.stickyTop)
               } else {
                  style.height = this.fixed ? this.height + 'px' : 'auto'
               }
            } else {
               // æ— éœ€å¸é¡¶æ—¶ï¼Œè®¾ç½®ä¼šé»˜è®¤çš„relative(nvue)和非nvue的static静态模式即可
               // #ifdef APP-NVUE
               style.position = 'relative'
               // #endif
               // #ifndef APP-NVUE
               style.position = 'static'
               // #endif
            }
            style.backgroundColor = this.bgColor
            return uni.$u.deepMerge(uni.$u.addStyle(this.customStyle), style)
         },
         // å¸é¡¶å†…容的样式
         stickyContent() {
            const style = {}
            if (!this.cssSticky) {
               style.position = this.fixed ? 'fixed' : 'static'
               style.top = this.stickyTop + 'px'
               style.left = this.left + 'px'
               style.width = this.width == 'auto' ? 'auto' : this.width + 'px'
               style.zIndex = this.uZindex
            }
            return style
         },
         uZindex() {
            return this.zIndex ? this.zIndex : uni.$u.zIndex.sticky
         }
      },
      mounted() {
         this.init()
      },
      methods: {
         init() {
            this.getStickyTop()
            // åˆ¤æ–­ä½¿ç”¨çš„æ¨¡å¼
            this.checkSupportCssSticky()
            // å¦‚果不支持css sticky,则使用js方案,此方案性能比不上css方案
            if (!this.cssSticky) {
               !this.disabled && this.initObserveContent()
            }
         },
         initObserveContent() {
            // èŽ·å–å¸é¡¶å†…å®¹çš„é«˜åº¦ï¼Œç”¨äºŽåœ¨js吸顶模式时,给父元素一个填充高度,防止"塌陷"
            this.$uGetRect('#' + this.elId).then((res) => {
               this.height = res.height
               this.left = res.left
               this.width = res.width
               this.$nextTick(() => {
                  this.observeContent()
               })
            })
         },
         observeContent() {
            // å…ˆæ–­æŽ‰ä¹‹å‰çš„观察
            this.disconnectObserver('contentObserver')
            const contentObserver = uni.createIntersectionObserver({
               // æ£€æµ‹çš„区间范围
               thresholds: [0.95, 0.98, 1]
            })
            // åˆ°å±å¹•顶部的高度时触发
            contentObserver.relativeToViewport({
               top: -this.stickyTop
            })
            // ç»‘定观察的元素
            contentObserver.observe(`#${this.elId}`, res => {
               this.setFixed(res.boundingClientRect.top)
            })
            this.contentObserver = contentObserver
         },
         setFixed(top) {
            // åˆ¤æ–­æ˜¯å¦å‡ºäºŽå¸é¡¶æ¡ä»¶èŒƒå›´
            const fixed = top <= this.stickyTop
            this.fixed = fixed
         },
         disconnectObserver(observerName) {
            // æ–­æŽ‰è§‚察,释放资源
            const observer = this[observerName]
            observer && observer.disconnect()
         },
         getStickyTop() {
            this.stickyTop = uni.$u.getPx(this.offsetTop) + uni.$u.getPx(this.customNavHeight)
         },
         async checkSupportCssSticky() {
            // #ifdef H5
            // H5,一般都是现代浏览器,是支持css sticky的,这里使用创建元素嗅探的形式判断
            if (this.checkCssStickyForH5()) {
               this.cssSticky = true
            }
            // #endif
            // å¦‚果安卓版本高于8.0,依然认为是支持css sticky的(因为安卓7在某些机型,可能不支持sticky)
            if (uni.$u.os() === 'android' && Number(uni.$u.sys().system) > 8) {
               this.cssSticky = true
            }
            // APP-Vue和微信平台,通过computedStyle判断是否支持css sticky
            // #ifdef APP-VUE || MP-WEIXIN
            this.cssSticky = await this.checkComputedStyle()
            // #endif
            // ios上,从ios6开始,都是支持css sticky的
            if (uni.$u.os() === 'ios') {
               this.cssSticky = true
            }
            // nvue,是支持css sticky的
            // #ifdef APP-NVUE
            this.cssSticky = true
            // #endif
         },
         // åœ¨APP和微信小程序上,通过uni.createSelectorQuery可以判断是否支持css sticky
         checkComputedStyle() {
            // æ–¹æ³•内进行判断,避免在其他平台生成无用代码
            // #ifdef APP-VUE || MP-WEIXIN
            return new Promise(resolve => {
               uni.createSelectorQuery().in(this).select('.u-sticky').fields({
                  computedStyle: ["position"]
               }).exec(e => {
                  resolve('sticky' === e[0].position)
               })
            })
            // #endif
         },
         // H5通过创建元素的形式嗅探是否支持css sticky
         // åˆ¤æ–­æµè§ˆå™¨æ˜¯å¦æ”¯æŒsticky属性
         checkCssStickyForH5() {
            // æ–¹æ³•内进行判断,避免在其他平台生成无用代码
            // #ifdef H5
            const vendorList = ['', '-webkit-', '-ms-', '-moz-', '-o-'],
               vendorListLength = vendorList.length,
               stickyElement = document.createElement('div')
            for (let i = 0; i < vendorListLength; i++) {
               stickyElement.style.position = vendorList[i] + 'sticky'
               if (stickyElement.style.position !== '') {
                  return true
               }
            }
            return false;
            // #endif
         }
      },
      beforeDestroy() {
         this.disconnectObserver('contentObserver')
      }
   }
</script>
<style lang="scss" scoped>
   .u-sticky {
      /* #ifdef APP-VUE || MP-WEIXIN */
      // æ­¤å¤„默认写sticky属性,是为了给微信和APP通过uni.createSelectorQuery查询是否支持css sticky使用
      position: sticky;
      /* #endif */
   }
</style>