Vue只在mousedown之后移动

Gia*_*omo 6 javascript mousedown vue.js vuejs2

如果首先单击元素,如何触发鼠标移动?我正在尝试将其用于音频播放器时间线.

.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)) + '%'}")
Run Code Online (Sandbox Code Playgroud)

方法:

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
},
Run Code Online (Sandbox Code Playgroud)

Roy*_*y J 19

您将希望mousedown在元素上设置一个侦听器来设置变量以指示拖动已开始.在窗口上放置一个监听器以捕获mouseup任何位置并取消设置变量.

mousemove如果您只对在元素内发生的拖动感兴趣,可以放置元素.否则你可以把mousemove听众放在上面,window这样你就可以到处抓住它.

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);
  }
});
Run Code Online (Sandbox Code Playgroud)
.dragstartzone {
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)