Html 如何设置 HTML5 范围输入的样式以在滑块前后具有不同的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18389224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:28:14  来源:igfitidea点击:

How to style HTML5 range input to have different color before and after slider?

csshtmlinputwebkit

提问by Shamoon

enter image description here

在此处输入图片说明

I want the left side to be green and the right side to be gray. As pictured above would be PERFECT. Preferably a pure CSS solution (only need to worry about WebKit).

我希望左侧为绿色,右侧为灰色。如上图所示将是完美的。最好是纯 CSS 解决方案(只需要担心 WebKit)。

Is such a thing possible?

这样的事情可能吗?

回答by deathangel908

Pure CSSsolution:

纯 CSS解决方案:

  • Chrome:Hide the overflow from input[range], and fill all the space left to thumb with shadow color.
  • IE:no need to reinvent the wheel: ::-ms-fill-lower
  • Firefoxno need to reinvent the wheel: ::-moz-range-progress
  • Chrome:隐藏从 的溢出input[range],并用阴影颜色填充拇指剩下的所有空间。
  • IE:无需重新发明轮子:::-ms-fill-lower
  • Firefox无需重新发明轮子:::-moz-range-progress

/*Chrome*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
    input[type='range'] {
      overflow: hidden;
      width: 80px;
      -webkit-appearance: none;
      background-color: #9a905d;
    }
    
    input[type='range']::-webkit-slider-runnable-track {
      height: 10px;
      -webkit-appearance: none;
      color: #13bba4;
      margin-top: -1px;
    }
    
    input[type='range']::-webkit-slider-thumb {
      width: 10px;
      -webkit-appearance: none;
      height: 10px;
      cursor: ew-resize;
      background: #434343;
      box-shadow: -80px 0 0 80px #43e5f7;
    }

}
/** FF*/
input[type="range"]::-moz-range-progress {
  background-color: #43e5f7; 
}
input[type="range"]::-moz-range-track {  
  background-color: #9a905d;
}
/* IE*/
input[type="range"]::-ms-fill-lower {
  background-color: #43e5f7; 
}
input[type="range"]::-ms-fill-upper {  
  background-color: #9a905d;
}
<input type="range"/>

回答by federico-t

Yes, it is possible. Though I wouldn't recommend it because input rangeis not really supported properly by all browsers because is an new element added in HTML5 and HTML5 is only a draft (and will be for long) so going as far as to styling it is perhaps not the best choice.

对的,这是可能的。虽然我不会推荐它,因为input range并不是所有浏览器都真正支持它,因为在 HTML5 中添加了一个新元素,而 HTML5 只是一个草稿(并且会持续很长时间)所以就样式而言它可能不是最好的选择。

Also, you'll need a bit of JavaScript too. I took the liberty of using jQuerylibrary for this, for simplicity purposes.

此外,您还需要一些 JavaScript。为了简单起见,我冒昧地使用jQuery库。

Here you go: http://jsfiddle.net/JnrvG/1/.

给你:http: //jsfiddle.net/JnrvG/1/

回答by dargue3

While the accepted answer is good in theory, it ignores the fact that the thumb then cannot be bigger than size of the track without being chopped off by the overflow: hidden. See this example of how to handle this with just a tiny bit of JS.

虽然理论上接受的答案是好的,但它忽略了这样一个事实,即拇指不能大于轨道的大小而不会被overflow: hidden. 请参阅此示例,了解如何仅使用一点点 JS 来处理此问题。

// .chrome styling Vanilla JS

document.getElementById("myinput").oninput = function() {
  this.style.background = 'linear-gradient(to right, #82CFD0 0%, #82CFD0 ' + this.value + '%, #fff ' + this.value + '%, white 100%)'
};
#myinput {
  background: linear-gradient(to right, #82CFD0 0%, #82CFD0 50%, #fff 50%, #fff 100%);
  border: solid 1px #82CFD0;
  border-radius: 8px;
  height: 7px;
  width: 356px;
  outline: none;
  transition: background 450ms ease-in;
  -webkit-appearance: none;
}
<div class="chrome">
  <input id="myinput" type="range" value="50" />
</div>

回答by James Parker

A small update to this one:

对此的一个小更新:

if you use the following it will update on the fly rather than on mouse release.

如果您使用以下内容,它将即时更新,而不是在鼠标释放时更新。

"change mousemove", function"

“更改鼠标移动”,功能”

<script>
$('input[type="range"]').on("change mousemove", function () {
    var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));

    $(this).css('background-image',
                '-webkit-gradient(linear, left top, right top, '
                + 'color-stop(' + val + ', #2f466b), '
                + 'color-stop(' + val + ', #d3d3db)'
                + ')'
                );
});</script>

回答by fedeghe

The previous accepted solution is not working any longer.

以前接受的解决方案不再有效

I ended up coding a simple function which wraps the rangeinto a styled container adding the bar that is needed before the cursor. I wrote this examplewhere easy to see the two colors 'blue' and 'orange' set in the css, so they can be quickly modified.

我最终编写了一个简单的函数,该函数将 包装range到一个样式容器中,在光标之前添加所需的栏。我写了这个例子,其中很容易看到css中设置的两种颜色“蓝色”和“橙色”,因此可以快速修改它们。

回答by htmn

Building on top of @dargue3'sanswer, if you want the thumb to be larger than the track, you want to fully take advantage of the <input type="range" />element and go cross browser, you need a little extra lines of JS & CSS.

建立在@dargue3 的答案之上,如果您希望拇指比轨道大,您希望充分利用<input type="range" />元素并跨浏览器,则需要一些额外的 JS 和 CSS 行。

On Chrome/Mozilla you can use the linear-gradienttechnique, but you need to adjust the ratio based on the min, max, valueattributes as mentioned hereby @Attila O.. You need to make sure you are not applying this on Edge, otherwise the thumb is not displayed. @Geoffrey Lallouéexplains this in more detail here.

在Chrome / Mozilla浏览器可以使用linear-gradient的技术,但你需要调整基础上的比例minmaxvalue属性提到这里@Attila O.。你需要确保你没有在 Edge 上应用它,否则不会显示拇指。@Geoffrey Lalloué这里更详细地解释了这一点

Another thing worth mentioning, is that you need to adjust the rangeEl.style.height = "20px";on IE/Older. Simply put this is because in this case "the height is not applied to the track but rather the whole input including the thumb". fiddle

另一件值得一提的是,您需要rangeEl.style.height = "20px";在 IE/Older 上调整。简单地说,这是因为在这种情况下“高度不应用于轨道,而是应用于包括拇指在内的整个输入”。小提琴

/**
 * Sniffs for Older Edge or IE,
 * more info here:
 * https://stackoverflow.com/q/31721250/3528132
 */
function isOlderEdgeOrIE() {
  return (
    window.navigator.userAgent.indexOf("MSIE ") > -1 ||
    !!navigator.userAgent.match(/Trident.*rv\:11\./) ||
    window.navigator.userAgent.indexOf("Edge") > -1
  );
}

function valueTotalRatio(value, min, max) {
  return ((value - min) / (max - min)).toFixed(2);
}

function getLinearGradientCSS(ratio, leftColor, rightColor) {
  return [
    '-webkit-gradient(',
    'linear, ',
    'left top, ',
    'right top, ',
    'color-stop(' + ratio + ', ' + leftColor + '), ',
    'color-stop(' + ratio + ', ' + rightColor + ')',
    ')'
  ].join('');
}

function updateRangeEl(rangeEl) {
  var ratio = valueTotalRatio(rangeEl.value, rangeEl.min, rangeEl.max);

  rangeEl.style.backgroundImage = getLinearGradientCSS(ratio, '#919e4b', '#c5c5c5');
}

function initRangeEl() {
  var rangeEl = document.querySelector('input[type=range]');
  var textEl = document.querySelector('input[type=text]');

  /**
   * IE/Older Edge FIX
   * On IE/Older Edge the height of the <input type="range" />
   * is the whole element as oposed to Chrome/Moz
   * where the height is applied to the track.
   *
   */
  if (isOlderEdgeOrIE()) {
    rangeEl.style.height = "20px";
    // IE 11/10 fires change instead of input
    // https://stackoverflow.com/a/50887531/3528132
    rangeEl.addEventListener("change", function(e) {
      textEl.value = e.target.value;
    });
    rangeEl.addEventListener("input", function(e) {
      textEl.value = e.target.value;
    });
  } else {
    updateRangeEl(rangeEl);
    rangeEl.addEventListener("input", function(e) {
      updateRangeEl(e.target);
      textEl.value = e.target.value;
    });
  }
}

initRangeEl();
input[type="range"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  width: 300px;
  height: 5px;
  padding: 0;
  border-radius: 2px;
  outline: none;
  cursor: pointer;
}


/*Chrome thumb*/

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  -moz-appearance: none;
  -webkit-border-radius: 5px;
  /*16x16px adjusted to be same as 14x14px on moz*/
  height: 16px;
  width: 16px;
  border-radius: 5px;
  background: #e7e7e7;
  border: 1px solid #c5c5c5;
}


/*Mozilla thumb*/

input[type="range"]::-moz-range-thumb {
  -webkit-appearance: none;
  -moz-appearance: none;
  -moz-border-radius: 5px;
  height: 14px;
  width: 14px;
  border-radius: 5px;
  background: #e7e7e7;
  border: 1px solid #c5c5c5;
}


/*IE & Edge input*/

input[type=range]::-ms-track {
  width: 300px;
  height: 6px;
  /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */
  background: transparent;
  /*leave room for the larger thumb to overflow with a transparent border */
  border-color: transparent;
  border-width: 2px 0;
  /*remove default tick marks*/
  color: transparent;
}


/*IE & Edge thumb*/

input[type=range]::-ms-thumb {
  height: 14px;
  width: 14px;
  border-radius: 5px;
  background: #e7e7e7;
  border: 1px solid #c5c5c5;
}


/*IE & Edge left side*/

input[type=range]::-ms-fill-lower {
  background: #919e4b;
  border-radius: 2px;
}


/*IE & Edge right side*/

input[type=range]::-ms-fill-upper {
  background: #c5c5c5;
  border-radius: 2px;
}


/*IE disable tooltip*/

input[type=range]::-ms-tooltip {
  display: none;
}

input[type="text"] {
  border: none;
}
<input type="range" value="80" min="10" max="100" step="1" />
<input type="text" value="80" size="3" />

回答by Wilson F

It's now supported with pseudo elements in each of WebKit, Firefox and IE. But, of course, it's different in each one. : (

现在,WebKit、Firefox 和 IE 中的每个伪元素都支持它。但是,当然,每个人的情况都不一样。:(

See this question's answers and/or search for a CodePen titled prettify <input type=range> #101for some solutions.

请参阅此问题的答案和/或搜索标题prettify <input type=range> #101为某些解决方案的 CodePen 。

回答by Krish

input type="range" min="0" max="50" value="0"  style="margin-left: 6%;width: 88%;background-color: whitesmoke;"

above code changes range input style.....

以上代码更改范围输入样式.....