如何在CSS/JavaScript中让滑块把手覆盖在实际的进度条之上?

前端开发 2026-07-10

在此输入图片描述

如图所示,滑块的滑柄始终位于边框下方。如何让它保持在边框之上,并且再也看不到滑柄下方的边框?

有没有办法在JavaScript代码中引用滑块的滑柄?到目前为止,我只能修改滑块本身,没法在脚本中同时修改滑柄。

这是CSS的滑块代码:

.slider
{
    -webkit-appearance: none;
    height: 12px;
    --pc: 0;
    --color: #000000;
    --bgcolor: transparent;
    --border: #000000;
    background: linear-gradient(to right, transparent 0 var(--pc), var(--bgcolor) var(--pc) 100%), var(--color);
    background-origin: content-box;
    outline: solid;
    outline-color: var(--border);
    border-radius: 10px;
    overflow: visible;
}

.slider::-webkit-slider-thumb
{
    -webkit-appearance: none;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    outline: solid;
    outline-color: #000000;
    background: #CC1818;
}

以下是我在脚本中创建滑块对象的方式: (每次调用函数切换到下一首歌时都会创建一个新的对象)

progressbar = document.createElement("input")
progressbar.className = "slider"
progressbar.value = 0
progressbar.max = audio.duration
progressbar.min = 0
progressbar.style.width = "75%"
progressbar.style.position = "absolute"
progressbar.style.bottom = "16%"
progressbar.type = "range"
progressbar.style.setProperty('--color', barcolor)
progressbar.style.setProperty('--bgcolor', barbgcolor)
progressbar.style.setProperty('--border', barbordercolor)
progressbar.oninput = function()
{
    audio.currentTime =  progressbar.value

    pc = (progressbar.value - progressbar.min) / (progressbar.max - progressbar.min) * 100;
    if (pc < 20) {pc++}
    progressbar.style.setProperty('--pc', pc + '%');
}

解决方案

假设你使用的是原生的 <input type="range">,在 .slider::-webkit-slider-runnable-track 上添加 position:relative,或在 ::-webkit-slider-thumb 上添加 position:relative,就能在Chrome上解决我的问题。

.slider
{
    -webkit-appearance: none;
    height: 12px;
    --pc: 0;
    --color: white;
    --bgcolor: transparent;
    --border: #000000;
    background: linear-gradient(to right, transparent 0 var(--pc), var(--bgcolor) var(--pc) 100%), var(--color);
    background-origin: content-box;
    outline: solid;
    outline-color: var(--border);
    border-radius: 10px;
    overflow: visible;
}

.slider-fixed::-webkit-slider-runnable-track {
  position: relative;
}

.slider::-webkit-slider-thumb
{
    -webkit-appearance: none;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    outline: solid;
    outline-color: #000000;
    background: #CC1818;
}
<input type="range"  class="slider" /> 
<input type="range"  class="slider slider-fixed" />
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章