gpt4 book ai didi

javascript - 当更改 html 选择的背景颜色时,第一个选项随之更改

转载 作者:行者123 更新时间:2023-11-28 09:44:53 25 4
gpt4 key购买 nike

我正在尝试创建一个 HTML 表单,其中包含多个选择元素,这些元素具有供用户选择颜色的颜色选项。我能够创建一个概念验证文档,该文档成功更改了选择的背景颜色属性以匹配所选选项的背景颜色。但是,第一个选项(其值为“none”,因此应该没有 bg 颜色)也会随着 select 元素的变化而变化。我不知道如何解决这个问题,这有点烦人。

概念验证文档的源代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Drop Down List Test</title>
<style>
select
{
border: 2px solid black;
width: 120px;
height: 30px;
}

select option { height: 30px; }

[value=none] { background-color: transparent; }
[value=red] { background-color: red ; }
[value=green] { background-color: green; }
[value=blue] { background-color: blue ; }
</style>
<script>
/*
This function is called by the onChange event in the form element below
The only input argument is a DOM reference to the form argument itself

If the value of the form element is NOT "none",
Then the background color will be whatever the user selected
Else, the background color is set to transparent
*/
function changeSelectBGColor(form_element)
{
if(form_element.value != "none")
form_element.style.backgroundColor = form_element.value;
else form_element.style.backgroundColor = "transparent";
}
</script>
</head>

<body>
<form>
<!--
When the user selects a color value in this drop-down,
the background color changes to reflect the user's selection
The onchange attribute calls the JS function defined above
-->
<select onchange="changeSelectBGColor(this)">
<option value="none" ></option>
<option value="red" ></option>
<option value="green"></option>
<option value="blue" ></option>
</select>
</form>
</body>

</html>

请原谅我相当奇怪的 OCD 间距约定。它使源代码对我而言更具可读性和可维护性。

有人对如何使这项工作有任何想法吗?如果可能的话,我想避免使用 jQuery 以保持这种简单和轻量级,但我愿意接受使用 jQuery 的建议。

最佳答案

您需要设置元素的初始颜色。将元素设置为透明从最近的背景颜色设置中提取,而不是从初始设置中提取。例如,设置初始/“无”背景颜色元素以匹配文档的实际背景颜色。

关于javascript - 当更改 html 选择的背景颜色时,第一个选项随之更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25298383/

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