Vue3+JS:实现进度条拖拽
在Vue 3中,可以通过结合Vue的响应式系统和原生HTML5的拖拽API来实现进度条拖拽的功能。以下是一个简单的实现示例:
<template>
<div>
<div class="progress-bar" ref="progressBar" @mousedown="handleMouseDown">
<div class="progress" :style="{ width: progress + '%' }"></div>
</div>
<div class="slider" ref="slider" @mousedown="handleSliderMouseDown"></div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const progressBar = ref(null);
const slider = ref(null);
const progress = ref(0);
let isDragging = false;
let startX = 0;
let startWidth = 0;
const handleMouseDown = (event) => {
isDragging = true;
startX = event.clientX - progressBar.value.getBoundingClientRect().left;
startWidth = progressBar.value.offsetWidth;
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
const handleMouseMove = (event) => {
if (isDragging) {
const x = event.clientX - startX;
const maxX = startWidth - slider.value.offsetWidth;
progress.value = Math.min(100, Math.max(0, (x / maxX) * 100));
}
};
const handleMouseUp = () => {
isDragging = false;
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
const handleSliderMouseDown = (event) => {
event.stopPropagation();
const x = event.clientX - progressBar.value.getBoundingClientRect().left;
const maxX = progressBar.value.offsetWidth - slider.value.offsetWidth;
progress.value = Math.min(100, Math.max(0, (x / maxX) * 100));
};
return { progressBar, slider, progress, handleMouseDown, handleSliderMouseDown };
}
};
</script>
<style>
.progress-bar {
position: relative;
height: 5px;
background-color: #ddd;
cursor: pointer;
user-select: none;
}
.progress {
position: absolute;
height: 100%;
back
评论已关闭