uni-app开发小程序实现竖向尺子,上面点可以左右滑动,并在下方输出多出cm实现的具体代码,刻度尺不可左右滑动
时间: 2025-01-04 17:37:41 浏览: 246
UniApp 开发小程序中的竖直尺子功能需要结合 Vue.js 的组件化思想和一些基础 CSS 来实现。下面是一个简单的示例,展示了如何创建一个可以左右滑动的点以及动态显示厘米值的竖直尺子组件:
```html
<template>
<view class="scale-ruler">
<!-- 横坐标轴 -->
<view class="ruler-axis" :style="{ height: rulerHeight + 'px', width: rulerWidth, backgroundColor: '#ccc' }"></view>
<!-- 竖直尺子 -->
<view class="ruler-scale" v-for="(item, index) in刻度Array" :key="index" :style="{ left: item.offset + 'px', height: '1px', backgroundColor: isFocused && (index === currentFocus ? '#ff0000' : '#ddd') }">
<!-- 刻度标记 -->
<text class="ruler-mark" :class="{ focused: isFocused && index === currentFocus }">{{ item.label }}</text>
</view>
<!-- 可滑动的点 -->
<view class="slider-point" :style="{ top: currentFocusOffset + 'px', backgroundColor: isFocused ? '#f00' : '#ccc' }"
@touchstart="onTouchStart($event)"
@touchmove="onTouchMove($event)"
@touchend="onTouchEnd($event)">
<text>{{ currentFocusLabel }} cm</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
rulerHeight: '300px', // 尺子的高度
rulerWidth: '100%', // 尺子的宽度
刻度Array: [
{ offset: '0', label: '0' },
{ offset: '2.5', label: '2.5' }, // 假设每2.5厘米一个刻度
... // 添加更多刻度...
],
currentFocus: 0, // 当前聚焦的刻度索引
currentFocusOffset: '0', // 当前聚焦刻度的位置
currentFocusLabel: '', // 当前刻度的标签
isFocused: false,
};
},
methods: {
onTouchStart(e) {
this.isFocused = true;
this.currentFocus = parseInt((e.touches[0].clientY - this.$refs.sliderPoint.offsetTop) / this.rulerHeight);
this.currentFocusOffset = this.calculateFocusPosition(this.currentFocus);
this.currentFocusLabel = this.calculateFocusLabel(this.currentFocus);
},
onTouchMove(e) {
const touchY = e.touches[0].clientY;
const newFocus = parseInt((touchY - this.$refs.sliderPoint.offsetTop) / this.rulerHeight);
if (newFocus !== this.currentFocus) {
this.currentFocus = newFocus;
this.currentFocusOffset = this.calculateFocusPosition(newFocus);
this.currentFocusLabel = this.calculateFocusLabel(newFocus);
}
},
onTouchEnd() {
this.isFocused = false;
},
calculateFocusPosition(index) {
return `${index * 2.5}px`; // 假设刻度间隔是2.5厘米
},
calculateFocusLabel(index) {
return index * 2.5; // 显示实际厘米数值
},
},
};
</script>
<style scoped>
.scale-ruler {
display: flex;
align-items: center;
}
.ruler-axis {
position: absolute;
bottom: 0;
}
.ruler-scale {
position: relative;
overflow: hidden;
white-space: nowrap;
}
.ruler-mark {
position: absolute;
transform-origin: center;
font-size: 14px;
transition: all 0.2s;
}
.slider-point {
position: relative;
cursor: pointer;
width: 20px;
height: 40px;
border-radius: 50%;
transition: background-color 0.2s;
}
</style>
```
在这个例子中,我们首先创建了一个横坐标轴和竖直刻度线组成的尺子,然后通过触摸事件控制滑动点的移动并实时更新显示的厘米值。注意,这个代码只是一个简化的示例,实际应用中可能需要考虑更多的边界情况和用户体验优化。
阅读全文
相关推荐
















