uni-app中实现元素拖动

2024-01-03 10:35:57

uni-app中实现元素拖动

1、代码示例
<template>
  <movable-area class="music-layout">
    <movable-view class="img-layout" :x="x" :y="y" direction="all">
      <img :src="musicDetail.bgUrl" :class="[ isPlay ? 'rotate-img' : '']" @click="onImgClick">
      <view class="small-circle"></view>
    </movable-view>
  </movable-area>
</template>

<script>
export default {
  name: "music-icon",
  props: {
    musicDetail: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      innerAudioContext: {},
      x: 300,
      y: 500,
      isPlay: true,
    }
  },
  watch: {
    musicDetail: {
      handler(newVal, oldVal) {
        if (newVal.music) {
          this.handlePlay();
        }
      },
      immediate: true
    }
  },
  methods:{
    handlePlay() {
      this.innerAudioContext = uni.createInnerAudioContext();
      this.innerAudioContext.src = this.musicDetail.music;
      this.innerAudioContext.startTime = 0;
      this.innerAudioContext.play();
      this.innerAudioContext.loop = true; // 循环播放
    },
    onImgClick() {
      this.isPlay = !this.isPlay;
      if (this.isPlay) {
        this.innerAudioContext.play();
      } else {
        this.innerAudioContext.pause();
      }
    }
  }
}
</script>

<style scoped lang="scss">

.music-layout {
  height: 100vh;
  width: 750rpx;
  top: 0;
  position: fixed;
  pointer-events: none; //鼠标事件可以渗透
}

.img-layout {
  position: relative;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  overflow: hidden;
  pointer-events: auto; //恢复鼠标事件
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
  .small-circle{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 20rpx;
    height: 20rpx;
    background-color: white;
    border-radius: 50%;
  }
}

.rotate-img {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  transform-origin: center center;
  animation: rotate 5s infinite linear;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

利用的是uni-app中的movable-area和movable-view两个组件配合实现

2、效果图展示

在这里插入图片描述

文章来源:https://blog.csdn.net/yangyanqin2545/article/details/135356559
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。