首页 > 解决方案 > 如果我的 html 文件中有超过 1 个 select2,如何更改特定 select2 的宽度?

问题描述

我的 HTML 文件中有超过 1 个 select2。我想为特定的 select2 设置一个宽度,为所有其他 select2 设置一个公共宽度。公共宽度正在影响所有选择的宽度,即使我试图通过 jquery 覆盖宽度,它也不会发生。

CSS

.select2-container {
    width: 100% !important;
}

HTML

<div class="col-md-12">
    <select class="select2 form-control m-t-15"  id="user_name">
        <option selected="selected">Select Name</option>
    </select>
    <select class="select2 form-control m-t-15"  id="user_roll">
        <option selected="selected">Select Roll</option>
    </select>
    <select class="select2 form-control m-t-15"  id="user_address">
        <option selected="selected">Select Address</option>
    </select>
</div>

查询

    $(".select2").select2();
    $("#user_address").select2({ width: '50%' });

预期结果:- id 为“user_address”的选择 2 的宽度应为 50%。

当前结果:- 所有选择 2 的宽度均为 100%

有人知道如何将 50% 的宽度设置为 id "user_address" 的 select2 吗?

标签: jqueryhtmlcss

解决方案


您已经为每个 select2 设置了 id,因此您可以使用其 id 设置特定 select2 的样式,例如让我们设置“user_roll”样式:

#user_roll{
//your styling here, noting that "#" is for the id just like the "." is for class
  }

推荐阅读