index.vue 17.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10
<template>
  <uni-scroll-view v-on="$listeners">
    <div
      ref="wrap"
      class="uni-scroll-view">
      <div
        ref="main"
        :style="{'overflow-x': scrollX?'auto':'hidden','overflow-y': scrollY?'auto':'hidden'}"
        class="uni-scroll-view">
        <div ref="content">
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
          <div
            v-if="refresherEnabled"
            ref="refresherinner"
            :style="{'background-color': refresherBackground, 'height': refresherHeight + 'px'}"
            class="uni-scroll-view-refresher">
            <div
              v-if="refresherDefaultStyle !== 'none'"
              class="uni-scroll-view-refresh">
              <div class="uni-scroll-view-refresh-inner">
                <svg
                  v-if="refreshState=='pulling'"
                  :style="{'transform': 'rotate('+ refreshRotate +'deg)'}"
                  fill="#2BD009"
                  class="uni-scroll-view-refresh__icon"
                  width="24"
                  height="24"
                  viewBox="0 0 24 24">
                  <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />
                  <path
                    d="M0 0h24v24H0z"
                    fill="none" />
                </svg>
                <svg
                  v-if="refreshState=='refreshing'"
                  class="uni-scroll-view-refresh__spinner"
                  width="24"
                  height="24"
                  viewBox="25 25 50 50">
                  <circle
                    cx="50"
                    cy="50"
                    r="20"
                    fill="none"
                    style="color: #2BD009;"
                    stroke-width="3"/>
                </svg>
              </div>
            </div>
            <slot
              v-if="refresherDefaultStyle=='none'"
              name="refresher"/>
          </div>
fxy060608's avatar
fxy060608 已提交
53 54 55 56 57 58 59 60 61
          <slot/>
        </div>
      </div>
    </div>
  </uni-scroll-view>
</template>
<script>
import scroller from 'uni-mixins/scroller/index'
import {
62 63
  supportsPassive,
  disableScrollBounce
fxy060608's avatar
fxy060608 已提交
64
} from 'uni-shared'
65

fxy060608's avatar
fxy060608 已提交
66 67 68
const passiveOptions = supportsPassive ? {
  passive: true
} : false
69 70 71 72

// const PULLING = 'pulling'
// const REFRESHING = 'refreshing'

fxy060608's avatar
fxy060608 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
export default {
  name: 'ScrollView',
  mixins: [scroller],
  props: {
    scrollX: {
      type: [Boolean, String],
      default: false
    },
    scrollY: {
      type: [Boolean, String],
      default: false
    },
    upperThreshold: {
      type: [Number, String],
      default: 50
    },
    lowerThreshold: {
      type: [Number, String],
      default: 50
    },
    scrollTop: {
      type: [Number, String],
      default: 0
    },
    scrollLeft: {
      type: [Number, String],
      default: 0
    },
    scrollIntoView: {
      type: String,
      default: ''
    },
    scrollWithAnimation: {
      type: [Boolean, String],
      default: false
    },
    enableBackToTop: {
      type: [Boolean, String],
      default: false
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    },
    refresherEnabled: {
      type: [Boolean, String],
      default: false
    },
    refresherThreshold: {
      type: Number,
      default: 45
    },
    refresherDefaultStyle: {
      type: String,
      default: 'back'
    },
    refresherBackground: {
      type: String,
      default: '#fff'
    },
    refresherTriggered: {
      type: [Boolean, String],
      default: false
fxy060608's avatar
fxy060608 已提交
132 133 134 135 136 137 138
    }
  },
  data () {
    return {
      lastScrollTop: this.scrollTopNumber,
      lastScrollLeft: this.scrollLeftNumber,
      lastScrollToUpperTime: 0,
139 140 141 142
      lastScrollToLowerTime: 0,
      refresherHeight: 0,
      refreshRotate: 0,
      refreshState: 'pulling'
fxy060608's avatar
fxy060608 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    }
  },
  computed: {
    upperThresholdNumber () {
      var val = Number(this.upperThreshold)
      return isNaN(val) ? 50 : val
    },
    lowerThresholdNumber () {
      var val = Number(this.lowerThreshold)
      return isNaN(val) ? 50 : val
    },
    scrollTopNumber () {
      return Number(this.scrollTop) || 0
    },
    scrollLeftNumber () {
      return Number(this.scrollLeft) || 0
    }
  },
  watch: {
    scrollTopNumber (val) {
      this._scrollTopChanged(val)
    },
    scrollLeftNumber (val) {
      this._scrollLeftChanged(val)
    },
    scrollIntoView (val) {
      this._scrollIntoViewChanged(val)
170 171 172 173 174 175 176 177
    },
    refresherTriggered (val) {
      // TODO
      if (val === true) {
        this._setRefreshState('refreshing')
      } else if (val === false) {
        this._setRefreshState('restore')
      }
fxy060608's avatar
fxy060608 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    }
  },
  mounted () {
    var self = this
    this._attached = true
    this._scrollTopChanged(this.scrollTopNumber)
    this._scrollLeftChanged(this.scrollLeftNumber)
    this._scrollIntoViewChanged(this.scrollIntoView)
    this.__handleScroll = function (e) {
      event.preventDefault()
      event.stopPropagation()
      self._handleScroll.bind(self, event)()
    }
    var touchStart = null
    var needStop = null
    this.__handleTouchMove = function (event) {
      var x = event.touches[0].pageX
      var y = event.touches[0].pageY
      var main = self.$refs.main
      if (needStop === null) {
        if (Math.abs(x - touchStart.x) > Math.abs(y - touchStart.y)) {
          // 横向滑动
          if (self.scrollX) {
            if (main.scrollLeft === 0 && x > touchStart.x) {
              needStop = false
              return
            } else if (main.scrollWidth === main.offsetWidth + main.scrollLeft && x < touchStart.x) {
              needStop = false
              return
            }
            needStop = true
          } else {
            needStop = false
          }
        } else {
          // 纵向滑动
          if (self.scrollY) {
            if (main.scrollTop === 0 && y > touchStart.y) {
              needStop = false
              return
            } else if (main.scrollHeight === main.offsetHeight + main.scrollTop && y < touchStart.y) {
              needStop = false
              return
            }
            needStop = true
          } else {
            needStop = false
          }
        }
      }
      if (needStop) {
        event.stopPropagation()
      }
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247

      if (self.refresherEnabled && self.refreshState !== 'refreshing' && touchStart && main.scrollTop === 0) {
        let dy = y - touchStart.y
        self.refresherHeight = dy

        let rotate = dy / self.refresherThreshold
        if (rotate > 1) {
          rotate = 1
        } else {
          rotate = rotate * 360
        }
        self.refreshRotate = rotate

        self.$trigger('refresherpulling', event, {
          deltaY: dy
        })
      }
fxy060608's avatar
fxy060608 已提交
248
    }
249

fxy060608's avatar
fxy060608 已提交
250 251
    this.__handleTouchStart = function (event) {
      if (event.touches.length === 1) {
252 253 254
        disableScrollBounce({
          disable: true
        })
fxy060608's avatar
fxy060608 已提交
255 256 257 258 259
        needStop = null
        touchStart = {
          x: event.touches[0].pageX,
          y: event.touches[0].pageY
        }
260 261 262
        if (self.refresherEnabled && self.refreshState !== 'refreshing' && self.$refs.main.scrollTop === 0) {
          self.refreshState = 'pulling'
        }
fxy060608's avatar
fxy060608 已提交
263 264
      }
    }
265
    this.__handleTouchEnd = function (event) {
266
      touchStart = null
267 268 269
      disableScrollBounce({
        disable: false
      })
270 271 272 273 274 275
      if (self.refresherHeight >= self.refresherThreshold) {
        self._setRefreshState('refreshing')
      } else {
        self.refresherHeight = 0
        self.$trigger('refresherabort', event, {})
      }
276
    }
fxy060608's avatar
fxy060608 已提交
277 278 279 280 281
    this.$refs.main.addEventListener('touchstart', this.__handleTouchStart, passiveOptions)
    this.$refs.main.addEventListener('touchmove', this.__handleTouchMove, passiveOptions)
    this.$refs.main.addEventListener('scroll', this.__handleScroll, supportsPassive ? {
      passive: false
    } : false)
282
    this.$refs.main.addEventListener('touchend', this.__handleTouchEnd, passiveOptions)
fxy060608's avatar
fxy060608 已提交
283
  },
284 285 286 287 288
  activated () {
    // 还原 scroll-view 滚动位置
    this.scrollY && (this.$refs.main.scrollTop = this.lastScrollTop)
    this.scrollX && (this.$refs.main.scrollLeft = this.lastScrollLeft)
  },
fxy060608's avatar
fxy060608 已提交
289 290 291 292 293 294
  beforeDestroy () {
    this.$refs.main.removeEventListener('touchstart', this.__handleTouchStart, passiveOptions)
    this.$refs.main.removeEventListener('touchmove', this.__handleTouchMove, passiveOptions)
    this.$refs.main.removeEventListener('scroll', this.__handleScroll, supportsPassive ? {
      passive: false
    } : false)
295
    this.$refs.main.removeEventListener('touchend', this.__handleTouchEnd, passiveOptions)
fxy060608's avatar
fxy060608 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  },
  methods: {
    scrollTo: function (t, n) {
      var i = this.$refs.main
      t < 0 ? t = 0 : n === 'x' && t > i.scrollWidth - i.offsetWidth ? t = i.scrollWidth - i.offsetWidth
        : n === 'y' && t > i.scrollHeight - i.offsetHeight && (t = i.scrollHeight - i.offsetHeight)
      var r = 0
      var o = ''
      n === 'x' ? r = i.scrollLeft - t : n === 'y' && (r = i.scrollTop - t)
      if (r !== 0) {
        this.$refs.content.style.transition = 'transform .3s ease-out'
        this.$refs.content.style.webkitTransition = '-webkit-transform .3s ease-out'
        if (n === 'x') {
          o = 'translateX(' + r + 'px) translateZ(0)'
        } else {
          n === 'y' && (o = 'translateY(' + r + 'px) translateZ(0)')
        }
        this.$refs.content.removeEventListener('transitionend', this.__transitionEnd)
        this.$refs.content.removeEventListener('webkitTransitionEnd', this.__transitionEnd)
        this.__transitionEnd = this._transitionEnd.bind(this, t, n)
        this.$refs.content.addEventListener('transitionend', this.__transitionEnd)
        this.$refs.content.addEventListener('webkitTransitionEnd', this.__transitionEnd)
        if (n === 'x') {
          // if (e !== 'ios') {
          i.style.overflowX = 'hidden'
          // }
        } else if (n === 'y') {
          i.style.overflowY = 'hidden'
        }

        this.$refs.content.style.transform = o
        this.$refs.content.style.webkitTransform = o
      }
    },
    _handleTrack: function ($event) {
      if ($event.detail.state === 'start') {
        this._x = $event.detail.x
        this._y = $event.detail.y
        this._noBubble = null
        return
      }
      if ($event.detail.state === 'end') {
        this._noBubble = false
      }
      if (this._noBubble === null && this.scrollY) {
        if (Math.abs(this._y - $event.detail.y) / Math.abs(this._x - $event.detail.x) > 1) {
          this._noBubble = true
        } else {
          this._noBubble = false
        }
      }
      if (this._noBubble === null && this.scrollX) {
        if (Math.abs(this._x - $event.detail.x) / Math.abs(this._y - $event.detail.y) > 1) {
          this._noBubble = true
        } else {
          this._noBubble = false
        }
      }
      this._x = $event.detail.x
      this._y = $event.detail.y
      if (this._noBubble) {
        $event.stopPropagation()
      }
    },
    _handleScroll: function ($event) {
      if (!($event.timeStamp - this._lastScrollTime < 20)) {
        this._lastScrollTime = $event.timeStamp
        let target = $event.target
        this.$trigger('scroll', $event, {
          scrollLeft: target.scrollLeft,
          scrollTop: target.scrollTop,
          scrollHeight: target.scrollHeight,
          scrollWidth: target.scrollWidth,
          deltaX: this.lastScrollLeft - target.scrollLeft,
          deltaY: this.lastScrollTop - target.scrollTop
        })
        if (this.scrollY) {
          if (target.scrollTop <= this.upperThresholdNumber && this.lastScrollTop - target.scrollTop > 0 && $event.timeStamp - this.lastScrollToUpperTime > 200) {
            this.$trigger('scrolltoupper', $event, {
              direction: 'top'
            })
            this.lastScrollToUpperTime = $event.timeStamp
          }
          if (target.scrollTop + target.offsetHeight + this.lowerThresholdNumber >= target.scrollHeight && this.lastScrollTop - target.scrollTop < 0 && $event.timeStamp - this.lastScrollToLowerTime > 200) {
            this.$trigger('scrolltolower', $event, {
              direction: 'bottom'
            })
            this.lastScrollToLowerTime = $event.timeStamp
          }
        }
        if (this.scrollX) {
          if (target.scrollLeft <= this.upperThresholdNumber && this.lastScrollLeft - target.scrollLeft > 0 && $event.timeStamp - this.lastScrollToUpperTime > 200) {
            this.$trigger('scrolltoupper', $event, {
              direction: 'left'
            })
            this.lastScrollToUpperTime = $event.timeStamp
          }
          if (target.scrollLeft + target.offsetWidth + this.lowerThresholdNumber >= target.scrollWidth && this.lastScrollLeft - target.scrollLeft < 0 && $event.timeStamp - this.lastScrollToLowerTime > 200) {
            this.$trigger('scrolltolower', $event, {
              direction: 'right'
            })
            this.lastScrollToLowerTime = $event.timeStamp
          }
        }
        this.lastScrollTop = target.scrollTop
        this.lastScrollLeft = target.scrollLeft
      }
    },
    _scrollTopChanged: function (val) {
      if (this.scrollY) {
        if (this._innerSetScrollTop) {
          this._innerSetScrollTop = false
        } else {
          if (this.scrollWithAnimation) {
            this.scrollTo(val, 'y')
          } else {
            this.$refs.main.scrollTop = val
          }
        }
      }
    },
    _scrollLeftChanged: function (val) {
      if (this.scrollX) {
        if (this._innerSetScrollLeft) {
          this._innerSetScrollLeft = false
        } else {
          if (this.scrollWithAnimation) {
            this.scrollTo(val, 'x')
          } else {
            this.$refs.main.scrollLeft = val
          }
        }
      }
    },
    _scrollIntoViewChanged: function (val) {
      if (val) {
        if (!/^[_a-zA-Z][-_a-zA-Z0-9:]*$/.test(val)) {
          console.group('scroll-into-view="' + val + '" 有误')
          console.error('id 属性值格式错误。如不能以数字开头。')
          console.groupEnd()
          return
        }
        var element = this.$el.querySelector('#' + val)
        if (element) {
          var mainRect = this.$refs.main.getBoundingClientRect()
          var elRect = element.getBoundingClientRect()
          if (this.scrollX) {
            var left = elRect.left - mainRect.left
            var scrollLeft = this.$refs.main.scrollLeft
            var x = scrollLeft + left
            if (this.scrollWithAnimation) {
              this.scrollTo(x, 'x')
            } else {
              this.$refs.main.scrollLeft = x
            }
          }
          if (this.scrollY) {
            var top = elRect.top - mainRect.top
            var scrollTop = this.$refs.main.scrollTop
            var y = scrollTop + top
            if (this.scrollWithAnimation) {
              this.scrollTo(y, 'y')
            } else {
              this.$refs.main.scrollTop = y
            }
          }
        }
      }
    },
    _transitionEnd: function (val, type) {
      this.$refs.content.style.transition = ''
      this.$refs.content.style.webkitTransition = ''
      this.$refs.content.style.transform = ''
      this.$refs.content.style.webkitTransform = ''
      var main = this.$refs.main
      if (type === 'x') {
        main.style.overflowX = this.scrollX ? 'auto' : 'hidden'
        main.scrollLeft = val
      } else if (type === 'y') {
        main.style.overflowY = this.scrollY ? 'auto' : 'hidden'
        main.scrollTop = val
      }
      this.$refs.content.removeEventListener('transitionend', this.__transitionEnd)
      this.$refs.content.removeEventListener('webkitTransitionEnd', this.__transitionEnd)
    },
481 482 483 484 485 486 487 488 489 490 491 492 493
    _setRefreshState (state) {
      switch (state) {
        case 'refreshing':
          this.refresherHeight = this.refresherThreshold
          this.$trigger('refresherrefresh', event, {})
          break
        case 'restore':
          this.refresherHeight = 0
          this.$trigger('refresherrestore', {}, {})
          break
      }
      this.refreshState = state
    },
fxy060608's avatar
fxy060608 已提交
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
    getScrollPosition () {
      const main = this.$refs.main
      return {
        scrollLeft: main.scrollLeft,
        scrollTop: main.scrollTop
      }
    }
  }
}
</script>
<style>
uni-scroll-view {
  display: block;
  width: 100%;
}

uni-scroll-view[hidden] {
  display: none;
}

.uni-scroll-view {
  position: relative;
  -webkit-overflow-scrolling: touch;
  width: 100%;
  /* display: flex; 时在安卓下会导致scrollWidth和offsetWidth一样 */
  height: 100%;
  max-height: inherit;
}
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588

.uni-scroll-view-refresher {
  position: relative;
  overflow: hidden;
}

.uni-scroll-view-refresh {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.uni-scroll-view-refresh-inner {
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 0;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0 1px 6px rgba(0, 0, 0, .117647), 0 1px 4px rgba(0, 0, 0, .117647);
}

.uni-scroll-view-refresh__spinner {
  transform-origin: center center;
  animation: uni-scroll-view-refresh-rotate 2s linear infinite;
}

.uni-scroll-view-refresh__spinner > circle {
  stroke: currentColor;
  stroke-linecap: round;
  animation: uni-scroll-view-refresh-dash 2s linear infinite;
}

@keyframes uni-scroll-view-refresh-rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@keyframes uni-scroll-view-refresh-dash {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }

  50% {
    stroke-dasharray: 89, 200;
    stroke-dashoffset: -35px;
  }

  100% {
    stroke-dasharray: 89, 200;
    stroke-dashoffset: -124px;
  }
}
fxy060608's avatar
fxy060608 已提交
589
</style>