原生js写一个滚动尺子
时间: 2024-05-08 15:20:03 浏览: 87
好的,下面是一个简单的原生JS实现滚动尺子的代码:
HTML代码:
```
<div class="slider-wrapper">
<div class="slider-track"></div>
<div class="slider-handle"></div>
</div>
```
CSS代码:
```
.slider-wrapper {
width: 300px;
height: 30px;
border: 1px solid #ccc;
position: relative;
}
.slider-track {
width: 100%;
height: 5px;
background-color: #ccc;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.slider-handle {
width: 20px;
height: 20px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
}
```
JS代码:
```
var sliderWrapper = document.querySelector('.slider-wrapper');
var sliderHandle = sliderWrapper.querySelector('.slider-handle');
var sliderTrack = sliderWrapper.querySelector('.slider-track');
var isDragging = false;
sliderHandle.addEventListener('mousedown', function(e) {
isDragging = true;
});
document.addEventListener('mousemove', function(e) {
if (isDragging) {
var x = e.clientX - sliderWrapper.offsetLeft;
if (x < 0) {
x = 0;
} else if (x > sliderWrapper.offsetWidth - sliderHandle.offsetWidth) {
x = sliderWrapper.offsetWidth - sliderHandle.offsetWidth;
}
var percent = x / (sliderWrapper.offsetWidth - sliderHandle.offsetWidth);
sliderHandle.style.left = percent * 100 + '%';
sliderTrack.style.width = percent * 100 + '%';
}
});
document.addEventListener('mouseup', function(e) {
isDragging = false;
});
```
说明:该代码使用了部分ES6语法,需要在支持ES6的浏览器中运行。该滚动尺子可拖动滑块调节滑块位置。
阅读全文