范围滑块

创建于 2024-12-03 / 27
字体: [默认] [大] [更大]

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


Default:

Square:

Round:

Image:

Value:

亲自试一试 »


创建范围滑块

步骤 1) 添加 HTML:

实例

<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
</div>
步骤 2) 添加 CSS:

实例

.slidecontainer {
  width: 100%; /* 外部容器的宽度 */
}

/* 滑块本身 */
.slider {
  -webkit-appearance: none;  /* 覆盖默认 CSS 样式 */
  appearance: none;
  width: 100%; /* Full-width */
  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; /* 设置特定的滑块手柄宽度 */
  height: 25px; /* 滑块手柄高度 */
  background: #4CAF50; /* 绿色背景 */
  cursor: pointer; /* 光标悬停 */
}

.slider::-moz-range-thumb {
 width: 25px; /* 设置特定的滑块手柄宽度 */
  height: 25px; /* 滑块手柄高度 */
  background: #4CAF50; /* 绿色背景 */
  cursor: pointer; /* 光标悬停 */
} 亲自试一试 »
步骤 3) 添加 JavaScript:

使用 JavaScript 创建动态范围滑块以显示当前值:

实例

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value; // 显示默认滑块值

// 更新当前滑块值(每次拖动滑块手柄)
slider.oninput = function() {
  output.innerHTML = this.value;
} 亲自试一试 »

圆形滑块

要创建圆形滑块句柄,请使用 border-radius 属性。

提示:如果您想要不相等的高度(在本例中为 15px 与 25px),请将滑块的高度设置为与滑块缩略图不同的值:

实例

.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: #4CAF50;
  cursor: pointer;
}

.slider::-moz-range-thumb {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: #4CAF50;
  cursor: pointer;
} 亲自试一试 »

滑块图标/图像

要创建滑块句柄图标/图像,请使用 background 属性并插入图像 url:

实例

.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;
} 亲自试一试 »

0 人点赞过