如何在带有小调色板的滑块上输出指针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%;
}
还-有比我使用的方法更容易显示红色->蓝色的颜色的方法吗?
答案 0 :(得分:1)
要通过滑块输入可靠地确定CSS渐变的RGB值,请考虑通过javascript定义渐变的颜色值。这使您能够同时进行以下操作:
例如,在您的脚本中,您可以通过颜色值数组定义颜色渐变:
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 + ')')
})
要获得完整的有效演示,请please see this 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%;
}