HTML:
<div class="container">
<div class="fill-area"></div>
<label for="range" id="range-value">0</label>
<input type="range" id="range" name="range" value="0" min="0" max="100" onmousemove="handleMouseMove(this.value)" onchange="handleMouseMove(this.value)" />
</div>
CSS:
/* 引入谷歌字体 */
@import url("https://fonts.googleapis.com/css2?family=Monoton&display=swap");
*{
/* 初始化 */
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* 渐变容器 */
.container{
/* 满屏 */
width: 100vw;
height: 100vh;
/* 弹性布局 水平+垂直居中 垂直排列 */
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
/* 渐变背景 */
background: linear-gradient(to right,#ff5c5c,#ffa860,#e3dc44,#57b02a);
}
/* 黑色背景(遮住渐变背景) */
.fill-area{
width: 100vw;
height: 100vh;
background: #333838;
/* 绝对定位 */
position: absolute;
left: 0;
top: 0;
z-index: 0;
/* 内阴影 */
box-shadow: inset 3px 3px 5px -1px #111;
/* 设置元素不对指针事件做出反应 */
pointer-events: none;
}
/* 滑动数值 */
label{
font-family: 'Monoton';
font-size: 8rem;
position: static;
z-index: 1;
color: #ec7474;
margin: -5rem 0 2rem;
}
label::after{
content: '%';
}
/* 滑动条 */
input[type=range]{
position: static;
z-index: 2;
width: 50vw;
height: 1rem;
background: rgba(88,36,36,0.8);
/* 去除滑动条的外貌 */
appearance: none;
border: none;
outline: none;
border-radius: 0.5rem;
/* 内阴影 */
box-shadow: inset 3px 3px 5px -1px #000;
}
/* 滑块 */
input[type=range]::-webkit-slider-thumb{
width: 4vw;
height: 4vw;
background: #eee;
/* 去除滑块的外貌 */
appearance: none;
border-radius: 50%;
cursor: pointer;
box-shadow: 5px 5px 8px -1px #000;
/* 阴影过渡效果 */
transition: box-shadow 0.3s ease-in-out;
}
/* 滑动条悬停时滑块的样式变化 */
input[type=range]:hover::-webkit-slider-thumb{
background: #fff;
box-shadow: 3px 3px 5px -1px #000;
}
JS:
// 要操作的元素
const rangeValue=document.querySelector('#range-value');
const range=document.querySelector('input[type="range"]');
const fillArea=document.querySelector('.fill-area');
// 滑块滑动函数
function handleMouseMove(value){
// hue-rotate是CSS中的颜色滤镜,可以设置不同的度数来改变颜色
const hueRotate="hue-rotate("+value+"deg)";
// 设置进度数值
rangeValue.textContent=value;
// 设置颜色滤镜
rangeValue.style.filter=hueRotate;
// 设置滑动条的颜色滤镜
range.style.filter=hueRotate;
// 显示渐变背景,改变黑色背景的宽度及位置
fillArea.style.left=value+'vw';
fillArea.style.width=100-value+'vw';
fillArea.style.filter=hueRotate;
}