native.js 1.8 KB
Newer Older
1
import { getNavigationBarHeight } from '../utils'
2 3 4 5 6 7 8 9 10 11 12 13 14

function getFixed ($el) {
  let fixed
  while ($el) {
    const style = getComputedStyle($el)
    const transform = style.transform || style.webkitTransform
    fixed = transform && transform !== 'none' ? false : fixed
    fixed = style.position === 'fixed' ? true : fixed
    $el = $el.parentElement
  }
  return fixed
}

Q
qiang 已提交
15 16 17 18
export default {
  name: 'Native',
  data () {
    return {
Q
qiang 已提交
19
      position: {
Q
qiang 已提交
20 21 22 23 24 25
        top: '0px',
        left: '0px',
        width: '0px',
        height: '0px',
        position: 'static'
      },
Q
qiang 已提交
26
      hidden: false
Q
qiang 已提交
27 28
    }
  },
Q
qiang 已提交
29 30 31 32
  created () {
    this.isNative = true
    this.onCanInsertCallbacks = []
  },
Q
qiang 已提交
33
  mounted () {
Q
qiang 已提交
34
    this._updatePosition()
Q
qiang 已提交
35
    this.$nextTick(() => {
Q
qiang 已提交
36
      this.onCanInsertCallbacks.forEach(callback => callback())
Q
qiang 已提交
37
    })
Q
qiang 已提交
38
    this.$on('uni-view-update', this._requestPositionUpdate)
Q
qiang 已提交
39 40
  },
  methods: {
Q
qiang 已提交
41 42 43 44
    _updatePosition () {
      const rect = (this.$refs.container || this.$el).getBoundingClientRect()
      this.hidden = rect.width === 0 || rect.height === 0
      if (!this.hidden) {
45 46 47 48
        const position = this.position
        position.position = getFixed(this.$el) ? 'absolute' : 'static'
        const keys = ['top', 'left', 'width', 'height']
        keys.forEach(key => {
Q
qiang 已提交
49
          let val = rect[key]
50 51
          val = key === 'top' ? val + (position.position === 'static' ? (document.documentElement.scrollTop || document.body.scrollTop || 0) : getNavigationBarHeight()) : val
          position[key] = val + 'px'
Q
qiang 已提交
52 53
        })
      }
Q
qiang 已提交
54 55 56 57 58 59 60 61 62
    },
    _requestPositionUpdate () {
      if (this._positionUpdateRequest) {
        cancelAnimationFrame(this._positionUpdateRequest)
      }
      this._positionUpdateRequest = requestAnimationFrame(() => {
        delete this._positionUpdateRequest
        this._updatePosition()
      })
Q
qiang 已提交
63 64 65
    }
  }
}