HTML5滑动区域选择元素 - 滑块元素 H5
在HTML5中,创建滑动区域选择元素(滑块)可以使用以下代码示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>滑动区域选择</title>
<style>
.slider-container {
width: 100%;
background-color: #f7f7f7;
margin: 10px 0;
position: relative;
}
.slider-range {
-webkit-appearance: none;
width: 100%;
height: 5px;
background-color: #007bff;
outline: none;
opacity: 0.7;
transition: opacity .2s;
}
.slider-range:hover {
opacity: 1;
}
.slider-thumb {
width: 20px;
height: 20px;
background-color: #007bff;
border: none;
border-radius: 50%;
cursor: pointer;
-webkit-appearance: none;
margin-top: -7px;
}
.slider-value {
position: absolute;
display: inline-block;
left: 50%;
transform: translateX(-50%);
color: #000;
}
</style>
</head>
<body>
<div class="slider-container">
<input type="range" min="1" max="100" value="50" class="slider-range" id="myRange">
<button class="slider-thumb" id="thumb"></button>
</div>
<div class="slider-value" id="sliderValue">50</div>
<script>
const slider = document.getElementById('myRange');
const thumb = document.getElementById('thumb');
const sliderValue = document.getElementById('sliderValue');
slider.addEventListener('input', () => {
const val = slider.value;
thumb.style.left = `${(val - 1) * 100 / (slider.max - slider.min)}%`;
sliderValue.innerText = val;
});
thumb.addEventListener('mousedown', function(e) {
const startX = e.clientX - thumb.offsetLeft;
function handler(e) {
const x = e.clientX - startX;
if (x < 0) {
thumb.style.left = '0%';
} else if (x > 100) {
thumb.style.left = '100%';
} else {
thumb.style.left = `${x}px`;
}
slider.value = Math.round((x / 100) * (slider.max - slider.min) + slider.min);
sliderValue.innerText = slider.value;
}
function clearHandler() {
document.removeEventListener('mousemove', handler);
document.removeEventListener('mouseup', clearHandler);
}
document.addEventListener('mousemove', handler);
document.addEventListener('mouseup', clearHandler);
});
</script>
</body>
</html>
这段代码实现了一个简单的滑动区域选择器,用户可以通过拖动滑块来改变区域选择的值。同时,滑块和区域选择器都有合适的样式,并且可以通过JavaScript代码进行交互。
评论已关闭