【问题标题】:Selection box background color html选择框背景颜色html
【发布时间】:2018-10-28 00:34:03
【问题描述】:

这是我的问题的参考图片。

我有一个 HTML 中的选择框,其颜色如上图和下面的代码所示。使用 CSS,我有一些类可以使各种 option 元素着色。如何使选定的项目也具有相同的颜色?

在图片中,红色被选中,但所选项目的背景仍然是白色。另外,有没有办法禁用悬停效果?看看当标记为orange 的项目悬停在它突出显示为蓝色时如何? (注意:按下按钮后,我使用 JavaScript 和 jQuery 将项目放入选择器中。)

<div class="selection">
    <select id="color">
        <option class="selectionpurple" value="purple">purple</option>
        <option class="selectionblue" value="blue">blue</option>
        <option class="selectionred" value="red">red</option>
        <option class="selectiongreen" value="green">green</option>
        <option class="selectionorange" value="orange">orange</option>
    </select>
</div>

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

您可以使用 jquery change() 函数来实现这一点。 change() 每次选择选项时运行。您只需要获取选定选项的值并使用 jquery css() 函数将该样式应用于选择。

var selected = $("select option:selected").val();
$('select').css('backgroundColor', selected);

$( "select" ).change(function () {
    console.log($(this).val());
    $('select').css('backgroundColor', $(this).val())
})
.red {
background-color : red;
}
.blue {
background-color : blue;
}
.green {
background-color : green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="text"> 
  <option value="red" class="red" selected>red</option> 
  <option value="blue" class="blue">blue</option>
  <option value="green" class="green">green</option>
</select>

【讨论】:

    【解决方案2】:

    var selected = $("select option:selected").val();
    $('select').css('backgroundColor', selected);
    
    $( "select" ).change(function () {
        console.log($(this).val());
        $('select').css('backgroundColor', $(this).val())
    })
    .red {
    background-color : red;
    }
    .blue {
    background-color : blue;
    }
    .green {
    background-color : green;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select name="text"> 
      <option value="red" class="red" selected>red</option> 
      <option value="blue" class="blue">blue</option>
      <option value="green" class="green">green</option>
    </select>

    【讨论】:

      猜你喜欢
      • 2011-12-14
      • 2012-10-01
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 2018-01-31
      相关资源
      最近更新 更多