从 select 中选择 2,要求不更改边框颜色。

Select2 from select with required not change border color.

我已经在我的表单中添加了这条 css 规则,以便在需要时添加橙色边框。

:required{
    border-color: #f8ac59 !important;
}

但这不适用于 Select2,当我尝试使用它时,我添加了这个人:

.select2-selection{
    border-color: #f8ac59 !important;
}

问题是所有 select2 都有橙色边框,我只需要来自 "select" Input 的 select2 具有必需的属性。我该如何解决这个问题。

HTML

<select class="form-control form-control-sm" data-width="100%" required>
    <option>Selec.</option>
    <option>Prueba 2 max with</option>
    <option>Prueba 3</option>
    <option>Prueba 4</option>
    <option>Prueba 5</option>
</select>

初始值:

$('select').each(function () {
        $(this).off('change');
        var width= $(this).attr("data-width") || '100px';
        $(this).select2({
            theme: 'bootstrap4',
            placeholder: "Buscar y Selecionar",
            width: width,
            dropdownAutoWidth: true
        });
    });
    <select id="mySelect" onchange="myFunction()" class="form-control form-control-sm" data-width="100%" required>
        <option value="one">Selec.</option>
        <option value="two">Prueba 2 max with</option>
        <option value="tree">Prueba 3</option>
        <option value="four">Prueba 4</option>
        <option value="five">Prueba 5</option>
    </select>

<script>
function myFunction() {
  var x = document.getElementById("mySelect");
  if(x.value == "two"){
    x.style.border = "solid orange";
  }
  else{
    x.style.border = "none";
  }
}
</script>

希望对您有所帮助

为了解决这个问题,有必要对脚本的初始化进行一些更改:

$('select').each(function () {
        $(this).off('change');
        var width= $(this).attr("data-width") || '100px';
        $(this).select2({
            theme: 'bootstrap4',
            placeholder: "Buscar y Selecionar",
            width: width,
            dropdownAutoWidth: true
        });
        var x = this.required;
        if(x){
            $(this).next().children().children().each(function(){
                $(this).css( "border-color", "#f8ac59" );
            });
        }
    });