uni-app中实现元素拖动

本文介绍了如何在uni-app中通过`movable-area`和`movable-view`组件配合,实现元素的拖动功能,并展示了如何结合图片点击事件控制音频播放和图片旋转效果。
摘要由CSDN通过智能技术生成

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、效果图展示

在这里插入图片描述

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值