【问题标题】:select2 apply styles to selectselect2 应用样式来选择
【发布时间】:2016-07-21 08:57:23
【问题描述】:

我从 cdn 中包含 select2 并将其应用于我的选择多个输入:

我的javascript:

$('select').select2();  

我的html:

<select id = "cars" name="cars[]" multiple = "multiple" required = "required">          

我的CSS:

#cars{
   background-color:red !important;
}

由于某种原因,每当我将 select2 应用于我拥有的任何选择时,我赋予此选择的所有特定样式都不再出现。我尝试通过 id 和 class 指定这些样式,它们都显示了,但是当我输入 $('select').select2(); 时,我为此选择指定的任何样式都不会显示。

我该如何解决这个问题?

【问题讨论】:

  • 检查呈现的选择 - 我怀疑 select2 会隐藏您的选择并创建它自己的选择,您必须对其进行样式覆盖 - 实际上我只是查看并替换了选择 - 此处示例 jsfiddle.net/ishanbakshi/fyhsz9ra
  • @DarrenSweeney 你说得对,我没有找到适合这个选择的风格。我该如何解决?
  • 用示例发布答案

标签: jquery html css select2


【解决方案1】:

Select2 隐藏选择并重新渲染

Example fiddle here with red background

已应用 CSS:

.select2-drop {
  background: red; /* !important not needed */
}

Fiddle with newer version of select2 (4.0.3)

已应用 CSS:

.select2-dropdown {
  background: red;
}

【讨论】:

  • 小提琴做你想做的事,所以也许你的代码中有其他东西在影响它
  • 可能是因为您使用的是旧版本?我使用的是 4.0.3 版
  • 好的,现在它工作了......但是你知道如何将样式应用于下拉菜单的元素,而不是整个下拉菜单吗?
  • 是的,只需将您的班级更改为:.select2-dropdown li { background: red; }
【解决方案2】:

select2 将选择显示设置为无并创建几乎像这样的元素:

<span class="select2 select2-container select2-container--default select2-container--below select2-container--focus" dir="rtl" style="width: 97px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-c968-container"><span class="select2-selection__rendered" id="select2-c968-container" title="ظرفیت - بیشترین">ظرفیت - بیشترین</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>

您必须使用检查元素来更改样式。 set select { ... } 无法再提供帮助,因为 select2.js 将选择元素显示设置为无。

【讨论】:

  • 这个 span 出现在哪里?
  • 在您的选择标签之后
猜你喜欢
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-11
  • 1970-01-01
  • 2013-06-09
  • 2010-11-15
  • 2011-02-18
相关资源
最近更新 更多