0

当用户选择一个值时,我正在尝试向 select2 框添加一个 CSS 样式。但我找不到如何做到这一点。我可以更改并添加到 css 文件中,但是即使显示占位符并且没有进行选择,它也会有这个。当我向 html 添加一个类时,它不会添加我需要完成的更改。

我需要在选择值时应用以下 CSS,因此当占位符替换为所选值的值时,触发 allowClear 事件时。这可能吗?我在任何地方都找不到它,而且我对这一切有点陌生,很抱歉这个愚蠢的问题(英语不是我的主要语言..)

border-bottom: 1px solid #b3b3b3 !important;

我使用以下脚本:

php/html

<select id="filteruser" class="select_test">
   <?php while ($row33 = $result33->fetch_assoc()) { ?>
        <option value="<?php echo $row33['user']; ?>"><?php echo $row33['name']; ?></option>
    <?php } $stmt33->close();?>
    
    </select>

选择 jquery

<script type="text/javascript">
    $(document).ready(function () {
$("#filteruser").select2( {
    placeholder: "Filter user",
    allowClear: true
    } );
$('#filteruser').val('<?php echo $_SESSION['user']; ?>'); // Select the option with a value of 'the current filter'
$('#filteruser').trigger('change'); // Notify any JS components that the value changed

} );
</script>

编辑:HTML 输出控制台:

 <select id="filteruser" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true">
            <option></option> 
        <option value="123">name3</option>
            <option></option> 
        <option value="124">name4</option>
            <option></option> 
        <option value="125">name5</option>
            <option></option> 
      
        
    </select><span class="select2 select2-container select2-container--default select2-container--below select2-container--open select2-container--focus" dir="ltr" style="width: 51px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="true" tabindex="0" aria-labelledby="select2-filteruser-container" aria-owns="select2-filteruser-results" aria-activedescendant="select2-filteruser-result-cx2p-123296"><span class="select2-selection__rendered" id="select2-filteruser-container"><span class="select2-selection__placeholder">Filter user</span></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>
4

3 回答 3

0

您必须在选项中提供: selectionCssClass:

$('#filteruser').select2({
      selectionCssClass: 'my-class-section'
    });

和CSS:

.my-class-section{
  border-bottom: 1px solid #b3b3b3 !important;
}
于 2021-09-17T22:23:08.373 回答
0

经过一番搜索,我想出了以下解决方案。我使用 jquery 来查找现有的类并向现有的类添加一个类。这样,我可以向该类添加样式并设置选择框的样式。

$('.select2').addClass('someclass')

在这里找到了答案:

如何使用 jquery 将两个类添加到现有类?

感谢所有的帮助!

于 2021-09-21T20:34:43.633 回答
0

使用 JavaScript 事件oninput,以便完成输入,函数将运行,如下面的代码片段

function demofunc() {
  document.getElementById("demo").style.borderBottom = "1px solid #b3b3b3"
}
select {
  outline: none;
  border: none;
}
<select oninput="demofunc()" id="demo">
  <option value="0">Select car:</option>
  <option value="1">Audi</option>
  <option value="2">BMW</option>
</select>

于 2021-09-17T22:18:15.527 回答