0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

0から伸ばすスライダー

Last updated at Posted at 2025-08-07

未加工のスライダー <input type="range"> は、端から端まで伸びますが、
マイナスからプラスの範囲を取るときには、0から伸ばしたい。

<input type="range">
css
input[type="range"] {
    appearance: none; /* ←標準のスタイルを解除します */
    width: 100%;
    height: 0.4rem;
    margin: 0;
    border: 1px solid gray;
    border-radius: 0.4rem;
    padding: 0;
    background-color: white;

    &::-webkit-slider-runnable-track {
		margin: 0 -5px; /* ←つまみが端まで行かない問題を解消します */
	}
}
javascript
const ranges = document.querySelectorAll('input[type="range"]');
const NegaColor = 'blue';
const PosiColor = 'red';
const backColor = 'white';

for (const range of ranges) {
	range.addEventListener('input', handler);
}

function handler() {

    // ゼロ点と入力値の位置(割合)を計算
	const range = this.max - this.min;
	const zero = 100 * (0 - this.min) / range;
	const ratio = 100 * (this.value - this.min) / range;

    // 0からマイナス方向へ伸ばす
    if (this.value < 0) {
		this.style.background = `linear-gradient(to right, ${backColor} ${ratio}%, ${NegaColor} ${ratio}% ${zero}%, ${backColor} ${zero}%)`;
		return;
	}

    // 0からプラス方向へ伸ばす
	if (this.value > 0) {
		this.style.background = `linear-gradient(to right, ${backColor} ${zero}%, ${PosiColor} ${zero}% ${ratio}%, ${backColor} ${ratio}%)`;
		return;
	}

    // 値が0の場合
	this.style.background = backColor;
}

<datalist>には未対応です。
appearance: none; で標準のスタイルを解除したスライダーに適用する方法は分からんかった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?