js 实现垂直标尺
实现垂直标尺的方法
使用HTML和CSS创建一个垂直标尺的基础结构。通过div元素定义标尺容器,利用CSS设置其样式和刻度线。
<div class="vertical-ruler"></div>
.vertical-ruler {
position: relative;
width: 30px;
height: 300px;
border-left: 1px solid #000;
margin-left: 20px;
}
动态生成刻度线
通过JavaScript动态生成刻度线,使用循环创建不同长度的刻度线并定位。
const ruler = document.querySelector('.vertical-ruler');
const height = 300; // 标尺总高度
const interval = 10; // 刻度间隔
for (let i = 0; i <= height; i += interval) {
const tick = document.createElement('div');
tick.style.position = 'absolute';
tick.style.left = '0';
tick.style.bottom = `${i}px`;
tick.style.width = i % 50 === 0 ? '20px' : '10px'; // 长刻度与短刻度
tick.style.height = '1px';
tick.style.backgroundColor = '#000';
ruler.appendChild(tick);
}
添加刻度数值
为长刻度添加数值标签,增强标尺的可读性。

for (let i = 0; i <= height; i += 50) {
const label = document.createElement('div');
label.style.position = 'absolute';
label.style.left = '25px';
label.style.bottom = `${i}px`;
label.style.transform = 'translateY(50%)';
label.style.fontSize = '12px';
label.textContent = i;
ruler.appendChild(label);
}
响应式调整标尺
通过监听窗口大小变化事件,动态调整标尺高度以适应不同屏幕尺寸。
function adjustRulerHeight() {
const viewportHeight = window.innerHeight;
ruler.style.height = `${viewportHeight * 0.8}px`;
}
window.addEventListener('resize', adjustRulerHeight);
adjustRulerHeight(); // 初始化时调用
自定义样式选项
通过CSS变量或JavaScript参数,允许自定义标尺的颜色、宽度和刻度间隔。

.vertical-ruler {
--ruler-color: #333;
--tick-interval: 10px;
}
const customRuler = (options) => {
const { color, interval } = options;
const ticks = document.querySelectorAll('.vertical-ruler div');
ticks.forEach(tick => {
tick.style.backgroundColor = color;
});
};
交互功能增强
为标尺添加拖拽或点击事件,使其能够与页面其他元素交互。
ruler.addEventListener('click', (e) => {
const yPos = e.clientY - ruler.getBoundingClientRect().top;
console.log(`Clicked at ${Math.round(yPos)}px`);
});
性能优化
对于高频更新的场景,使用requestAnimationFrame减少重绘开销。
function updateRuler() {
requestAnimationFrame(() => {
// 更新逻辑
});
}
兼容性处理
确保代码在旧版本浏览器中正常运行,必要时添加Polyfill或降级方案。
if (!Element.prototype.append) {
Element.prototype.append = function(...nodes) {
nodes.forEach(node => this.appendChild(node));
};
}






