Vue 实现带拖动功能的时间轴
<template>
<div class="timeline">
<div
class="timeline-item"
v-for="(item, index) in items"
:key="index"
:style="{ left: item.left + '%' }"
@mousedown="handleMouseDown(item, $event)"
>
<div class="timeline-content">
{{ item.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ content: 'Event 1', left: 20 },
{ content: 'Event 2', left: 50 },
{ content: 'Event 3', left: 80 }
],
draggingItem: null,
startX: 0,
timelineWidth: 0
};
},
methods: {
handleMouseDown(item, e) {
this.draggingItem = item;
this.startX = e.clientX;
this.$el.addEventListener('mousemove', this.handleMouseMove);
this.$el.addEventListener('mouseup', this.handleMouseUp);
this.timelineWidth = this.$el.offsetWidth;
},
handleMouseMove(e) {
if (this.draggingItem) {
const deltaX = e.clientX - this.startX;
this.draggingItem.left = this.calcLeft(deltaX);
this.startX = e.clientX;
}
},
handleMouseUp() {
this.draggingItem = null;
this.startX = 0;
this.$el.removeEventListener('mousemove', this.handleMouseMove);
this.$el.removeEventListener('mouseup', this.handleMouseUp);
},
calcLeft(deltaX) {
const newLeft = this.draggingItem.left + deltaX / this.timelineWidth * 100;
return Math.max(0, Math.min(100, newLeft));
}
}
};
</script>
<style scoped>
.timeline {
position: relative;
user-select: none;
}
.timeline-item {
position: absolute;
width: 6px;
height: 6px;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
z-index: 10;
}
.timeline-content {
position: absolute;
width: 100px;
white-space: nowrap;
background: #fff;
padding: 5px;
border: 1px solid #ddd;
border-radius: 4px;
transform: translateX(-50%) translateY(-50%);
left: 50%;
top: -30px;
}
</style>
这个简化版的Vue时间轴组件包含了基本的拖动功能。组件的每个项目都可以通过拖动来改变它们在时间轴上的位置。代码示例中包含了必要的HTML模板、JavaScript逻辑和CSS样式,以展示如何实现这一功能。
评论已关闭