我尝试使用多个选择元素创建一个HTML表单,这些元素具有供用户选择颜色的彩色选项。我能够创建概念验证文档,成功更改选择的背景颜色属性以匹配所选选项的背景颜色。但是,第一个选项(其值为#34;无"因此应该没有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的建议持开放态度。
答案 0 :(得分:0)
您需要设置元素的初始颜色。将元素设置为透明会从最近的背景颜色设置中提取,而不是从初始设置中提取。例如,设置initial /“none”background-color元素以匹配文档的实际背景颜色。