【问题标题】:How to change ListBox selected items' background color in Asp.Net如何在 Asp.Net 中更改 ListBox 所选项目的背景颜色
【发布时间】:2023-03-07 06:57:01
【问题描述】:

列表框

  <asp:ListBox ID="YearListBox" runat="server" Rows="11" SelectionMode="Multiple" AutoPostBack="True"></asp:ListBox>

如何将所选项目的背景设置为蓝色。 我尝试了以下解决方案,但在 chrome 中无法正常工作。

 int[] YearIndexes = YearListBox.GetSelectedIndices();
            for (int i = 0; i < YearIndexes.Length; i++)
            {
               //do something...
                YearListBox.Items[YearIndexes[i]].Attributes.Add("style", "background-color:blue");
            }

我们可以看到这张图片 [1] 上选中的项目的背景颜色是灰色的,但是这张图片 [2] 上的项目的背景属性是蓝色的。

似乎浏览器的默认样式覆盖了我的背景属性。

【问题讨论】:

  • 我想在回发后将所选项目的背景颜色设置为蓝色。

标签: c# css asp.net listbox


【解决方案1】:

您可以通过以下三种方式进行操作:

1. 尝试在列表项中提供style,如下所述:

<asp:ListItem style="background-color:red">Item 2</asp:ListItem>

2. 您可以从后面的代码中更改它,如下所述: Change color of list item

3.您可以如下应用css:

CSS:

.listContainer option {
    background-color: gray;
}

HTML:

<asp:ListBox runat="server" ID="listTest" CssClass="listContainer">
    <Items>
        <asp:ListItem >Test 1</asp:ListItem>
        <asp:ListItem >Test 2</asp:ListItem>
        <asp:ListItem >Test 3</asp:ListItem>
    </Items>
</asp:ListBox>

注意: 第四种方法是使用 Javasript 或 JQuery。但是当您想在运行时更改它时,这将很有用

【讨论】:

  • 我只想更改 SELECTED 项目的背景,而不是所有项目。
【解决方案2】:

首先,我会使用类而不是在代码中定义颜色(只是以后更容易更改)。

编辑: 您要求更改 UI 的行为方式,您可能会混淆用户。据我所知,无法覆盖应用于选定项目的默认灰色和蓝色样式。如果您必须这样做,那么您需要查看某种自定义控件。

这将在您想要的区域内,因此您可以对其应用完全自定义:reinventing a drop-down with css and jquery/

Custom SelectBox

【讨论】:

  • 这不适用于多选。
  • 确实如此,但不是您希望的那样。你也可以这样做:#YearListBox option[selected] { background: red; } 但是你仍然会得到浏览器的默认颜色
  • 感谢您的回答。我将尝试自定义选择框并实现回发事件。
  • 顺便说一下,所选项目在 chrome 中是灰色但在 IE11 中是蓝色,所以我想将颜色统一为绿色。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2010-10-16
相关资源
最近更新 更多