当改变背景颜色的html选择,第一个选项改变它
When changing background-color of html select, first option changes with it
我试图创建一个HTML表单与几个选择元素,有颜色的选项供用户选择颜色。我能够创建一个概念验证文档,它成功地更改了选择的background-color属性,以匹配所选选项的background-color。然而,第一个选项(其值为"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的建议。
您需要设置元素的初始颜色。将元素设置为透明将从最近的背景色设置中提取,而不是从初始设置中提取。例如,设置初始的/"none" background-color元素来匹配文档的实际背景色。
相关文章:
- 而循环只设置php中输入字段中的第一个值
- 错误:$injector:modulerr模块错误(我的第一个SPA应用程序)
- IE11中的第二个调用取消了第一个Fetch API调用
- Javascript XMLHttpRequest——只有第一个POST请求有效
- 使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
- 将OnClick函数设置为<ul>,最后一个ul是擦除第一个ul-s
- RxJS油门行为;立即获取第一个值
- Angular UI网格:如何通过第一个UI网格中的按钮使第二个UI网格可见
- 选择多个实例中的第一个
- 如何在调用下一个请求之前完成第一个Ajax Get请求
- Lodash:返回对象的第一个键,该对象的值(即数组)中有一个给定的元素(即字符串)
- 看起来第一个console.log是'It’不太对
- 与杜兰达尔合作的第一个JavaScript项目.尝试从第三方 API 获取数据
- 节点发布错误对象的第一个“属性”
- Javascript:表单验证getElementById仅返回第一个id元素
- 仅将 CSS 规则应用于
中的第一个 ,而不分配类/ID - JS在隐藏未定义的值后仅从数组中返回第一个id的值
- Hov 我用 javascript 改变风格,只影响第一个 ul
- 可以'当第一个select的值改变时,让jquery设置select输入的值
- Jquery使用.text()可以改变bootstrap类的第一个span,但不能改变第二个span