如何创建:范围滑块

学习如何使用 CSS 和 JavaScript 创建自定义范围滑块。

默认:

方块:

圆点:

图像:

值:

亲自试一试

创建范围滑块

第一步 - 添加 HTML:

<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
</div>

第二步 - 添加 CSS:

.slidecontainer {
  width: 100%; /* 外部容器的宽度 */
{}
/* The slider itself */
.slider {
  -webkit-appearance: none;  /* 覆盖默认 CSS 样式 */
  appearance: none;
  width: 100%; /* 全宽 */
  height: 25px; /* 指定的高度 */
  background: #d3d3d3; /* 灰色背景 */
  outline: none; /* 移除轮廓 */
  opacity: 0.7; /* 设置透明度(用于鼠标悬停时的鼠标悬停效果) */
  -webkit-transition: .2s; /* 0.2秒的过渡效果 */
  transition: opacity .2s;
{}
/* 鼠标悬停效果 */
.slider:hover {
  opacity: 1; /* 鼠标悬停时完全显示 */
{}
/* 滑块手柄(使用 -webkit-(Chrome、Opera、Safari、Edge)和 -moz-(Firefox)来覆盖默认外观) */
.slider::-webkit-slider-thumb {
  -webkit-appearance: none; /* 覆盖默认外观 */
  appearance: none;
  width: 25px; /* Set a specific slider handle width */
  height: 25px; /* Slider handle height */
  background: #04AA6D; /* Green background */
  cursor: pointer; /* Cursor when hovering */
{}
.slider::-moz-range-thumb {
  width: 25px; /* Set a specific slider handle width */
  height: 25px; /* Slider handle height */
  background: #04AA6D; /* Green background */
  cursor: pointer; /* Cursor when hovering */
{}

亲自试一试

Step 3 - Add JavaScript:

Create a dynamic range slider with JavaScript to display the current value:

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value; // Display the default slider value
// Update the current slider value (every time you drag the slider thumb)
slider.oninput = function() {
  output.innerHTML = this.value;
{}

亲自试一试

Circular slider

To create a circular slider handle, use: border-radius property.

Tip:If you want unequal heights (15 pixels and 25 pixels in this example), set the slider height to a different value than the slider thumb:

Sample

.slider {
  -webkit-appearance: none;
  width: 100%;
  height: 15px;
  border-radius: 5px;  
  background: #d3d3d3;
  outline: none;
  opacity: 0.7;
  -webkit-transition: .2s;
  transition: opacity .2s;
{}
.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  border-radius: 50%; 
  background: #04AA6D;
  cursor: pointer;
{}
.slider::-moz-range-thumb {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: #04AA6D;
  cursor: pointer;
{}

亲自试一试

Slider icon/image

To create a slider handle with an icon/image, use: background Insert the image URL of the property:

Sample

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 23px;
  height: 24px;
  border: 0;
  background: url('contrasticon.png');
  cursor: pointer;
{}
.slider::-moz-range-thumb {
  width: 23px;
  height: 25px;
  border: 0;
  background: url('contrasticon.png');
  cursor: pointer;
{}

亲自试一试