繁体   English   中英

如何输出滑块的 RGB 值?

[英]How can I output the RGB value of a slider?

我将如何输出带有小调色板的滑块上的指针 RGB 值?

HTML:

<div>
<input class="slider" type="range" min="0" max="255" value="127" />
</div>

CSS:

.slider {
display: inline;
-webkit-apperance: none;
height: 25px;
border-radius: 6px;
background: linear-gradient(to right, rgb(255, 0, 0), rgb(255, 125, 0), rgb(255, 255, 0), rgb(125, 255, 0), rgb(0, 255, 0), rgb(0, 255, 125), rgb(0, 255, 255), rgb(0, 125, 255), rgb(0, 0, 255) );
outline: none;
width: 35%;
}

另外 - 有没有比我做的方法更简单的方法来显示红色->蓝色的这些颜色?

要通过滑块输入可靠地确定 CSS 渐变的 RGB 值,请考虑通过 javascript 定义渐变的颜色值。 这使您能够:

  • 根据滑块值计算颜色和
  • 在 html 上指定 CSS 渐变(以保证一致性)

例如,在您的脚本中,您可以通过颜色值数组定义颜色渐变:

var colors = [
  [255, 0, 0], 
  [255, 125, 0], 
  [255, 255, 0], 
  [125, 255, 0], 
  [0, 255, 0], 
  [0, 255, 125], 
  [0, 255, 255], 
  [0, 125, 255], 
  [0, 0, 255]
];

然后,您可以通过以下方式计算滑块的背景 css 值:

slider.style.background = 'linear-gradient(to right ' + 
colors.reduce(function(style, color) { return style + ', rgb('+color[0]+','+color[1]+','+color[2]+')'; }, '') + 
')';

最后,您可以为滑块元素分配一个change事件侦听器,并使用colours数组从输入值中导出 RGB 颜色:

// The change event is defined on the input event
input.addEventListener('change', function(event) {

    // Derive lookup index from input element attributes
  var max = event.target.max;
  var min = event.target.min;
  var range = (max - min);

  // Calculate current lookup index to fetch current and next colour
  var frac = event.target.value / event.target.max;
  var offset = (colors.length - 1) * frac;
  var index = Math.min(Math.floor(offset), colors.length - 2);

  // Extract current and next colour from current slider position
  var colorNext = colors[ index + 1 ];
  var colorCurr = colors[ index ];
  var colorFrac = offset - index;

    // Linear interpolation utility used to compute blend between current and next colour
  function mix(from, to, frac) {
    return parseInt((to - from) * frac + from);
  }

    // Compute colour values for each channel
  var r = mix(colorCurr[0], colorNext[1], colorFrac);
  var g = mix(colorCurr[1], colorNext[1], colorFrac);
  var b = mix(colorCurr[2], colorNext[2], colorFrac);

    // The current colour based on slider position
  console.log('rgb(' + r + ',' + g + ',' + b + ')')
})

有关完整的工作演示,请参阅此 jsFiddle - 希望对您有所帮助!

更新

请确保您的 HTML 已更新为:

<div class="slider">
<input type="range" min="0" max="255" value="127" />
</div>

并且您的 CSS 更新为:

.slider {
display: block; 
height: 25px;
border-radius: 6px; 
outline: none;
}

.slider input { 
  width:100%;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM