我有一个js函数,可以在更改时控制select元素的外观。但是,我需要的一件事是代码从start开始运行,这样当元素加载选定的选项时,应该已经应用了类。
的CSS:
select {height: 50px; width: 80px; border: solid 1px #c8c8c8; color:rgba(0, 0, 0, 0);}
select:focus, #select:focus {
color:black;
}
.lightgrey {background: lightgrey}
.green {background:green}
.orange {background:orange}
.yellow {background:yellow}
.red {background:red}
.purple {background:purple}
JavaScript的:
function colourFunction(select) {
var colour = select.options[select.selectedIndex].className;
select.className = colour;
select.blur();
}
选择
<select class="selectElement" runat="server" id="dropdown_" onchange="colourFunction(this)">
<option selected="selected" class="lightgrey" value="N">N</option>
<option class="green" value="G">G</option>
<option class="orange" value="O">O</option>
<option class="yellow" value="A">A</option>
<option class="red" value="R">R</option>
<option class="purple" value="U">U</option>
</select>
我希望N的类在加载时应用颜色:rgba(0,0,0,0);
答案 0 :(得分:4)
如果你正在使用jquery:
$(function(){
//all onload actions you want
});
如果你想坚持使用纯粹的js
document.onreadystatechange=function(){
//all onload actions you want
}
答案 1 :(得分:4)
如果您希望JS在页面加载时运行,那么您可以使用“window.onload”命令。
window.onload = function()
{
colourFunction(select);
};
答案 2 :(得分:1)
问题是你的变更函数正在期待一个对象所以你需要在加载时得到一个句柄
你需要:
window.onload = function()
{
a = document.getElementById("dropdown_")
a.selectedIndex = 1//or 0
colourFunction(a);
};
全:
<style>
select {height: 50px; width: 80px; border: solid 1px #c8c8c8; color:rgba(0, 0, 0, 0);}
select:focus, #select:focus {
color:black;
}
.lightgrey {background: lightgrey}
.green {background:green}
.orange {background:orange}
.yellow {background:yellow}
.red {background:red}
.purple {background:purple}
</style>
<body>
<script>
function colourFunction(select) {
var colour = select.options[select.selectedIndex].className;
select.className = colour;
select.blur();
}
window.onload = function()
{
a = document.getElementById("dropdown_")
a.selectedIndex = 1//or 0
colourFunction(a);
};
</script>
<select runat="server" id="dropdown_" onchange="colourFunction(this)">
<option class="lightgrey" value="N">N</option>
<option class="green" value="G">G</option>
<option class="orange" value="O">O</option>
<option class="yellow" value="A">A</option>
<option class="red" value="R">R</option>
<option class="purple" value="U">U</option>
</select>