js实现手机端滑块滑动效果
时间: 2023-11-27 18:02:51 浏览: 117
你可以使用touch事件来实现手机端滑块滑动效果。以下是一个简单的示例代码:
HTML:
```html
<div class="slider">
<div class="slider-bar"></div>
<div class="slider-thumb"></div>
</div>
```
CSS:
```css
.slider {
position: relative;
width: 200px;
height: 10px;
background-color: #ddd;
}
.slider-bar {
position: absolute;
top: 50%;
left: 0;
width: 100%;
height: 2px;
background-color: #333;
transform: translateY(-50%);
}
.slider-thumb {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background-color: #333;
border-radius: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
}
```
JavaScript:
```javascript
var slider = document.querySelector('.slider');
var thumb = slider.querySelector('.slider-thumb');
var startX, thumbLeft;
thumb.addEventListener('touchstart', function(event) {
startX = event.touches[0].clientX;
thumbLeft = parseInt(window.getComputedStyle(thumb).left);
});
thumb.addEventListener('touchmove', function(event) {
event.preventDefault();
var moveX = event.touches[0].clientX - startX;
var newLeft = thumbLeft + moveX;
if (newLeft < 0) {
newLeft = 0;
} else if (newLeft > slider.offsetWidth - thumb.offsetWidth) {
newLeft = slider.offsetWidth - thumb.offsetWidth;
}
thumb.style.left = newLeft + 'px';
});
thumb.addEventListener('touchend', function(event) {
// do something when thumb is released
});
```
这个示例代码会创建一个横向的滑块,滑块的宽度是200px,高度是10px。滑块的背景颜色是灰色,滑块条是黑色的。滑块的滑块是一个小圆球,颜色也是黑色的。当滑块被拖动时,滑块的位置会跟着变化。
阅读全文