如何创建:范围滑块
学习如何使用 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; /* 设置特定的滑块手柄宽度 */ height: 25px; /* 滑块手柄高度 */ background: #04AA6D; /* 绿色背景 */ cursor: pointer; /* 鼠标悬停时的光标 */ } .slider::-moz-range-thumb { width: 25px; /* 设置特定的滑块手柄宽度 */ height: 25px; /* 滑块手柄高度 */ background: #04AA6D; /* 绿色背景 */ cursor: pointer; /* 鼠标悬停时的光标 */ }
第三步 - 添加 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
属性。
提示:如果您想要不等的高度(本例中为 15 像素与 25 像素),请将滑块的高度设置为与滑块拇指不同的值:
实例
.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; }
滑块图标/图像
要创建一个带有图标/图片的滑块手柄,请使用 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; }