要使一个范围滑块的拇指在大的圆形中,并使其出现在滑块轨道上,可以通过以下步骤实现:
以下是一个示例代码,实现了上述步骤:
HTML:
<div class="slider-container">
<div class="track"></div>
<div class="thumb"></div>
</div>
CSS:
.slider-container {
width: 200px;
height: 200px;
border-radius: 50%;
position: relative;
}
.track {
width: 100%;
height: 10px;
border-radius: 5px;
background-color: #ccc;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.thumb {
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #f00;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
JavaScript:
var thumb = document.querySelector('.thumb');
var track = document.querySelector('.track');
thumb.addEventListener('mousedown', startDrag);
thumb.addEventListener('touchstart', startDrag);
function startDrag(event) {
event.preventDefault();
document.addEventListener('mousemove', drag);
document.addEventListener('touchmove', drag);
document.addEventListener('mouseup', stopDrag);
document.addEventListener('touchend', stopDrag);
}
function drag(event) {
var container = document.querySelector('.slider-container');
var containerRect = container.getBoundingClientRect();
var trackRect = track.getBoundingClientRect();
var mouseX = event.clientX || event.touches[0].clientX;
var mouseY = event.clientY || event.touches[0].clientY;
var offsetX = mouseX - containerRect.left;
var offsetY = mouseY - containerRect.top;
var angle = Math.atan2(offsetY - containerRect.height / 2, offsetX - containerRect.width / 2);
var radius = containerRect.width / 2 - trackRect.width / 2;
var thumbX = Math.cos(angle) * radius + containerRect.width / 2;
var thumbY = Math.sin(angle) * radius + containerRect.height / 2;
thumb.style.left = thumbX + 'px';
thumb.style.top = thumbY + 'px';
}
function stopDrag() {
document.removeEventListener('mousemove', drag);
document.removeEventListener('touchmove', drag);
document.removeEventListener('mouseup', stopDrag);
document.removeEventListener('touchend', stopDrag);
}
这个示例代码创建了一个范围滑块,滑块的拇指可以在大的圆形中移动,并且始终出现在滑块轨道上。你可以根据需要自定义样式和添加动画效果。
领取专属 10元无门槛券
手把手带您无忧上云