我的表单中有一个,有 4 个不同的选项(项目) 我需要做的是在没有 PostBack 的情况下从客户端设置不同的颜色。
项目:
- 选择...(白色)
- 完成(绿色)
- 运行(黄色)
- 在 SEV1 中等待(红色)
有人可以帮我解决这个问题吗?
编辑(使用下拉代码)
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Select...</asp:ListItem>
<asp:ListItem>Complete</asp:ListItem>
<asp:ListItem>Running</asp:ListItem>
<asp:ListItem>Waiting in SEV 1</asp:ListItem>
<asp:ListItem>No Batch</asp:ListItem>
</asp:DropDownList>
我只是为此寻找解决方案,但还没有成功。这就是为什么我还没有尝试任何东西。
最佳答案
此标记对每个项目应用不同的背景颜色,并设置 onchange
事件处理程序:
<asp:DropDownList ID="DropDownList1" runat="server" onchange="SetDropDownListColor(this);">
<asp:ListItem style="background-color: White !important;" >Select...</asp:ListItem>
<asp:ListItem style="background-color: Green !important;" >Complete</asp:ListItem>
<asp:ListItem style="background-color: Yellow !important;" >Running</asp:ListItem>
<asp:ListItem style="background-color: Red !important;" >Waiting in SEV 1</asp:ListItem>
<asp:ListItem style="background-color: Blue !important;" >No Batch</asp:ListItem>
</asp:DropDownList>
以下 Javascript 确保选择框的颜色与所选项目的颜色相匹配:
function SetDropDownListColor(ddl) {
for (var i = 0; i < ddl.options.length; i++) {
if (ddl.options[i].selected) {
switch (i) {
case 0:
ddl.style.backgroundColor = 'White';
return;
case 1:
ddl.style.backgroundColor = 'Green';
return;
case 2:
ddl.style.backgroundColor = 'Yellow';
return;
case 3:
ddl.style.backgroundColor = 'Red';
return;
case 4:
ddl.style.backgroundColor = 'Blue';
return;
}
}
}
}
!important
修饰符设置在列表项的标记中,以覆盖在 Javascript 函数中为整个控件设置的背景颜色。
为了在回发后保留 DropDownList 的颜色,可以将以下代码行添加到 Javascript block 中。它为页面的 load
事件定义了一个处理程序,其中所选项目的颜色应用于选择框:
window.addEventListener('load', function () { SetDropDownListColor(document.getElementById('<%= DropDownList1.ClientID %>')); }, false);
关于c# - 在 asp :DropDownList Items 中设置不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36926663/