javascript - 如何输出滑块的 RGB 值?
问题描述
如何在带有小调色板的滑块上输出指针 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%;
}
推荐阅读
- maven - 无法在 Eclipse 的 Maven 项目中找到 bin 文件夹
- android - FragmentScenario 和嵌套的 NavHostFragments 在 Instrumentation 测试中未按预期执行导航
- r - R在数据框中查找替换
- javascript - MOGRT 中的 Premiere Pro Extendscript 复选框选择
- c# - 如何将元素插入数组C#
- core-data - 如何在共享容器中加载新的 Core Data 文件?
- bash - Grep 返回 'grep: node_list.txt: No such file or directory' 错误
- clojure - 如何在 Clojure 中嵌套 require?
- scala - 如何使用 BehaviorTestKit 来验证是否生成了正确的孩子
- haskell - GHCI - 提示颜色在 Windows 上不起作用