简体   繁体   English

在下拉列表中更改选择时更改文本颜色

[英]change text color on change of selection in dropdown list

I have a drop-down list of colors, and when selected, i want to change a value of css font color to the value of the selection. 我有一个颜色下拉列表,选中后,我想将css字体颜色的值更改为选择的值。

How can i do this? 我怎样才能做到这一点?

<select name="color">
          <option value="white" selected="selected">white</option>
          <option value="black">black</option>
          <option value="red">red</option>
          <option value="light blue">light blue</option>
          <option value="dark blue">dark blue</option>
          <option value="light green">light green</option>
          <option value="dark dreen">dark green</option>
          <option value="yellow">yellow</option>
          <option value="orange">orange</option>
          <option value="pink">pink</option>
          <option value="purple">purple</option>
          <option value="gray">gray</option>
        </select>

The css i want to change (its the text in a textfield) 我要改变的CSS(它在文本字段中的文本)

#create form .text {
    height: 50px;
    width: 500px;
    font-size: 36px;
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    font-weight: bold;
    color:#fff;
}

This will work for colors except light/dark blue/green : to make them work, remove the spaces in the value attributes of the corresponding option tags (and fix the typo in dark dreen) 这将适用于除浅/深蓝/绿色以外的颜色:使它们工作,删除相应option标签的value属性中的空格(并在暗绿色中修复拼写错误)

<script language="javascript">
  function setColor()
  {
    var color = document.getElementById("color").value;
    document.getElementById("txtID").style.color = color;
  }
</script>

<select id="color" onclick="setColor();">...</select>

This is really easy using jQuery (or most of the library's) 使用jQuery(或大多数库)非常容易

$('#color').change(function(){
   $('#create form .text').css('color', $(this).val());
});  

I think the code is pretty self explaining 我认为代码非常自我解释

EDIT 编辑
Just noticed some of your values are not real colors, you could use a switch for these cases, or decide to give them a value with the css color name: http://www.w3schools.com/css/css_colornames.asp 只是注意到你的一些值不是真正的颜色,你可以使用开关来处理这些情况,或者决定给它们一个带有css颜色名称的值: http//www.w3schools.com/css/css_colornames.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM