1 回答

TA貢獻1862條經驗 獲得超6個贊
最好的方法是使用CSS Variables將顏色傳遞給偽選擇器。我在下面整理了一個非常簡單的例子:
const input = document.querySelector( 'input' );
input.addEventListener( 'input', event => {
// This assigns the strength of the color to a CSS variable, which will in turn style the slider.
input.style.setProperty( '--color', `rgba(${input.value},0,0,1)`);
})
:root {
--color: rgba(0,0,0,1);
}
input[type=range] {
width: 100%;
height: 1em;
appearance: none;
-webkit-appearance: none;
background: linear-gradient( 90deg, black, red );
}
input[type=range]::-webkit-slider-thumb {
background: var(--color, white);
appearance: none;
-webkit-appearance: none;
width: 20px;
height: 20px;
border-radius: 20px;
border: 1px solid white;
}
<input type="range" value="1" min="0" max="255" step="1" />
這里的優雅之處在于它也與所有舊瀏覽器很好地兼容,因為您可以為那些懶得使用現代瀏覽器的人定義默認的白色。
不,JS 中無法訪問偽元素,因為它們……技術上不存在。
- 1 回答
- 0 關注
- 118 瀏覽
添加回答
舉報