gpt4 book ai didi

javascript - 一个颜色选择器用于多种颜色(背景、前景和文本)

转载 作者:行者123 更新时间:2023-11-28 02:23:55 25 4
gpt4 key购买 nike

我有一个按预期工作的颜色选择器

HTML:

<input id="cyan" class="colorPicker" style="vertical-align: middle;" class="grabbable" type="range" min="0" max="255" step="1" value="255">  
<input id="magenta" class="colorPicker" style="vertical-align: middle;" class="grabbable" type="range" min="0" max="255" step="1" value="255">
<input id="yellow" class="colorPicker" style="vertical-align: middle;" class="grabbable" type="range" min="0" max="255" step="1" value="255">

JavaScript:

var colorPicker = document.getElementsByClassName( "colorPicker" );
for( var i = 0; i < colorPicker.length; i++ )
{
colorPicker[i].addEventListener( "input", function(){
var cyan = document.getElementById( "cyan" ).value,
magenta = document.getElementById( "magenta" ).value,
yellow = document.getElementById( "yellow" ).value;

document.body.style.backgroundColor = "rgb(" + cyan + ", " + magenta + ", " + yellow + ")";
localStorage.setItem( "cyan", cyan );
localStorage.setItem( "magenta", magenta );
localStorage.setItem( "yellow", yellow );
});
}

我希望能够在屏幕上使用同一个颜色选择器,但有一个单选按钮或下拉菜单来选择要更改的其他颜色值。

希望这是清楚的。我是 JavaScript 的新手,知道它强大而灵活。我只是不知道如何实现这一点。

谢谢。

最佳答案

你的意思是这样的?我添加了 HTML select 元素并附加了事件。

var colorPicker = document.getElementsByClassName( "colorPicker" );
for( var i = 0; i < colorPicker.length; i++ )
{
colorPicker[i].addEventListener( "input", function(){
var cyan = document.getElementById( "cyan" ).value,
magenta = document.getElementById( "magenta" ).value,
yellow = document.getElementById( "yellow" ).value;

document.body.style.backgroundColor = "rgb(" + cyan + ", " + magenta + ", " + yellow + ")";
localStorage.setItem( "cyan", cyan );
localStorage.setItem( "magenta", magenta );
localStorage.setItem( "yellow", yellow );
});
}

var colorPickerSelect = document.getElementById("colorPickerSelect");
colorPickerSelect.addEventListener('change', function() {
document.body.style.backgroundColor = colorPickerSelect.value;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="cyan" class="colorPicker" style="vertical-align: middle;" class="grabbable" type="range" min="0" max="255" step="1" value="255">
<input id="magenta" class="colorPicker" style="vertical-align: middle;" class="grabbable" type="range" min="0" max="255" step="1" value="255">
<input id="yellow" class="colorPicker" style="vertical-align: middle;" class="grabbable" type="range" min="0" max="255" step="1" value="255">
<br/>
<select id="colorPickerSelect">
<option>red</option>
<option>green</option>
<option>blue</option>
</select>

关于javascript - 一个颜色选择器用于多种颜色(背景、前景和文本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48047220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com