vue实现游标尺
Vue 实现游标尺的方法
使用 SVG 绘制游标尺
在 Vue 中可以通过 SVG 实现游标尺,利用 SVG 的线条和文本元素绘制刻度。以下是一个简单的实现方式:

<template>
<div class="ruler-container">
<svg width="100%" height="50" class="ruler">
<line x1="0" y1="0" x2="100%" y2="0" stroke="black" stroke-width="2" />
<template v-for="i in ticks">
<line
:x1="i * 10"
:y1="0"
:x2="i * 10"
:y2="i % 10 === 0 ? 20 : 10"
stroke="black"
stroke-width="1"
/>
<text
v-if="i % 10 === 0"
:x="i * 10"
y="35"
text-anchor="middle"
>
{{ i }}
</text>
</template>
</svg>
</div>
</template>
<script>
export default {
data() {
return {
ticks: Array.from({ length: 101 }, (_, i) => i)
}
}
}
</script>
<style>
.ruler-container {
width: 100%;
overflow-x: auto;
}
.ruler {
min-width: 1000px;
}
</style>
使用 CSS 和动态样式
另一种方法是使用 CSS 和动态样式生成游标尺:

<template>
<div class="ruler">
<div
v-for="i in ticks"
:key="i"
class="tick"
:style="{ left: `${i * 10}px` }"
:class="{ major: i % 10 === 0 }"
>
<span v-if="i % 10 === 0" class="label">{{ i }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
ticks: Array.from({ length: 101 }, (_, i) => i)
}
}
}
</script>
<style>
.ruler {
position: relative;
height: 30px;
border-bottom: 2px solid #000;
width: 1000px;
overflow-x: auto;
}
.tick {
position: absolute;
bottom: 0;
width: 1px;
height: 10px;
background: #000;
}
.tick.major {
height: 20px;
}
.label {
position: absolute;
top: 22px;
left: -10px;
font-size: 12px;
}
</style>
添加交互功能
要实现可拖动的游标,可以添加鼠标事件处理:
<template>
<div class="ruler-container" @mousemove="handleMouseMove">
<div class="ruler">
<!-- 刻度代码同上 -->
</div>
<div class="cursor" :style="{ left: cursorPosition + 'px' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
cursorPosition: 0,
ticks: Array.from({ length: 101 }, (_, i) => i)
}
},
methods: {
handleMouseMove(event) {
const rect = this.$el.getBoundingClientRect()
this.cursorPosition = event.clientX - rect.left
}
}
}
</script>
<style>
.cursor {
position: absolute;
top: 0;
width: 2px;
height: 30px;
background: red;
pointer-events: none;
}
</style>
响应式设计
确保游标尺在不同屏幕尺寸下正常工作:
// 在组件中添加
mounted() {
window.addEventListener('resize', this.updateRulerWidth)
},
beforeDestroy() {
window.removeEventListener('resize', this.updateRulerWidth)
},
methods: {
updateRulerWidth() {
// 根据容器宽度调整刻度密度
}
}
这些方法提供了从基础到交互式的游标尺实现方案,可以根据具体需求进行调整和扩展。






