Vue只在mousedown之后移动

Vue只在mousedown之后移动

本文介绍了Vue只在mousedown之后移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果首先点击元素,我怎么能触发mousemove?
我正在尝试将其用于音频播放器时间轴。

How can I trigger a mousemove only if the element is clicked first?I'm trying to utilize this for an audio player timeline.

.player__time--bar(@mousedown="setNewCurrentPosition($event)")
    .slider(role="slider" aria-valuemin="0" :aria-valuenow="currentPosition" :aria-valuemax="trackTotalDuration" aria-orientation="horizontal")
        .player__time--bar-current-position(:style="{width:  (100 / (trackTotalDuration / currentPosition)) + '%'}")

方法:

setNewCurrentPosition(e) {
    let tag = e.target
    // if the click is not on 'slider', grab div with class 'slider'
    if (e.target.className === 'player__time--bar') tag = e.target.firstElementChild
    else if (e.target.className === 'player__time--bar-current-position') tag = e.target.parentElement
    const pos = tag.getBoundingClientRect()
    const seekPos = (e.clientX - pos.left) / pos.width
    this.currentPosition = parseInt(this.trackTotalDuration * seekPos)
    // updates the time in the html
    this.$refs.player.currentTime = this.currentPosition
},


推荐答案

你想要一个 mousedown 的监听器设置变量以指示拖动开始的元素。在窗口放置一个监听器,在任何地方捕获 mouseup 并取消设置变量。

You will want to have a mousedown listener on your element that sets a variable to indicate dragging started. Put a listener on the window to catch mouseup anywhere and unset the variable.

你可以放 mousemove 如果您只对拖动元素内部的元素感兴趣。否则你可以把 mousemove 监听器放在窗口上,这样你就可以在任何地方找到它。

You can put mousemove on the element if you are only interested in dragging that happens inside the element. Otherwise you can put the mousemove listener on window so you catch it everywhere.

new Vue({
  el: '#app',
  data: {
    dragging: false,
    x: 'no',
    y: 'no'
  },
  methods: {
    startDrag() {
      this.dragging = true;
      this.x = this.y = 0;
    },
    stopDrag() {
      this.dragging = false;
      this.x = this.y = 'no';
    },
    doDrag(event) {
      if (this.dragging) {
        this.x = event.clientX;
        this.y = event.clientY;
      }
    }
  },
  mounted() {
    window.addEventListener('mouseup', this.stopDrag);
  }
});
.dragstartzone {
  background-color: red;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <div class="dragstartzone" @mousedown="startDrag" @mousemove="doDrag">Start dragging here</div>
  <div>X: {{x}}, Y: {{y}}</div>
</div>

这篇关于Vue只在mousedown之后移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:41