1

如何为下拉列表中的每个 selectlistitem 设置样式?我可以给每个项目一个 id 并访问 in css 吗?我正在尝试更改每个项目的背景颜色...

这是代码:

@Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Red" },
                       new { value = 1 , text = "Blue" },
                       new { value = 2 , text = "Green"},

                    },
                  "value",
                  "text",
                   2))
4

2 回答 2

1

Html.DropDownListFor 呈现 a ,所以我不知道你为什么说你没有使用标签。

CSS 不关心服务器端代码,只关心呈现的 HTML,所以如果您遇到问题,请始终向我们展示呈现的 HTML 和您的 CSS。

无论如何,为您的元素设置样式(请记住,因为是 CSS 中的“替换元素”,所以样式设置的机会是有限的,但您可以做一些很酷的事情:http ://bavotasan.com/2011/style-select-box-仅使用 css/

您可以覆盖 id="" 的属性,这样您就可以在 CSS 中使用元素选择器,如下所示:

 @Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
                      new List<Object>{ 
                           new { value = 0 , text = "Red" },
                           new { value = 1 , text = "Blue" },
                           new { value = 2 , text = "Green"},

                        },
                      "value",
                      "text",
                       2), new { id = "mySelect" })


        #mySelect { width: 135px; }
//or
 @Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
                      new List<Object>{ 
                           new { value = 0 , text = "Red" },
                           new { value = 1 , text = "Blue" },
                           new { value = 2 , text = "Green"},

                        },
                      "value",
                      "text",
                       2), new { class = "dropdown" })

但是,如果您在局部视图中使用此 DropDownListFor,则 id="" 属性在文档中将不是唯一的,这是非法的。尝试使用利用上下文的不同选择器,例如后代选择器。

于 2014-03-27T12:19:25.227 回答
0

您应该能够使用 css 伪选择器,例如:

option:nth-child(1) {
    background: red;
}
于 2014-03-27T12:21:11.430 回答