123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- <template>
- <view
- class="wk-drag-button"
- :style="{
- top: top + 'px',
- left: left + 'px',
- transition: transitionStyle
- }"
- @touchstart="handleTouchStart"
- @touchmove.stop.prevent="handleTouchMove"
- @touchend="handleTouchEnd"
- @click="handleClick">
- <slot />
- </view>
- </template>
- <script>
- export default {
- name: 'WkDragButton',
- props: {
- // 距离上有下左的安全距离
- padding: {
- type: String,
- default: '116 20 70 20'
- },
- // 初始位置距离底部的距离
- bottom: {
- type: Number,
- default: 70
- },
-
- width: {
- type: Number,
- default: uni.upx2px(100)
- },
- height: {
- type: Number,
- default: uni.upx2px(100)
- }
- },
- data() {
- return {
- timer: null,
- clientWidth: 0,
- clientHeight: 0,
- itemWidth: 0,
- itemHeight: 0,
-
- left: 0,
- top: 0,
- transitionStyle: 'none'
- }
- },
- computed: {
- // 安全距离
- safeArea() {
- return this.padding.split(' ')
- },
- dragStyle() {
- return {
- top: this.top + 'px',
- left: this.left + 'px',
- transition: this.transitionStyle
- }
- }
- },
- created() {
- this.initButton()
- },
- methods: {
- initButton() {
- const sysInfo = uni.getSystemInfoSync()
- this.clientWidth = sysInfo.windowWidth
- this.clientHeight = sysInfo.windowHeight
- // 设置位置
- this.left = this.clientWidth - this.width - this.safeArea[1]
- this.top = this.clientHeight - this.height - this.bottom
- },
-
- handleClick(evt) {
- this.$emit('click', evt)
- },
- handleTouchStart() {
- this.transitionStyle = 'none'
- },
- handleTouchMove(e) {
- const touch = e.changedTouches[0]
- this.left = touch.clientX - this.width / 2
- this.top = touch.clientY - this.height / 2
- },
- handleTouchEnd(e) {
- this.transitionStyle = 'all 0.3s'
- // 手指放开left位置
- if (this.left > this.clientWidth / 2) {
- this.left = this.clientWidth - this.width - this.safeArea[1]
- } else {
- this.left = this.safeArea[3]
- }
- // 手指放开top位置
- if (this.top < this.safeArea[0]) {
- this.top = this.safeArea[0]
- } else if (this.top > this.clientHeight - this.height - this.safeArea[2]) {
- // 不低于最低
- this.top = this.clientHeight - this.height - this.safeArea[2]
- }
- }
- }
- }
- </script>
- <style lang="scss">
- .wk-drag-button {
- position: fixed;
- z-index: 1;
- display: flex;
- justify-content: center;
- align-items: center;
- transition: all 0.3s;
- pointer-events: auto;
- }
- </style>
|