如何为输入元素的文本着色

时间:2016-05-15 22:52:15

标签: jquery css css3

我的表单中有令牌输入,因此我希望每个以逗号分隔的令牌具有不同的颜色背景。我的问题是我如何按值设置每个元素的样式,还是可以在值中使用id?

我想要

  • 红色以使用红色背景,
  • 蓝色使用蓝色背景,
  • 绿色使用绿色背景,

我该怎么做才能做到这一点?这是我的代码:

<input value="red,blue,green"
       type="text"
       id="exampleInlineTags"
       class="form-control token-example-field"
       name="search"
       placeholder="Enter tags" />

1 个答案:

答案 0 :(得分:2)

您无法原生地设置输入值的样式,因为它假定使用其他内部HTML标记(这是文字,您需要真正的子元素!)

解决方法是使用contenteditable DIV

function toColorTokens() {
  $(this).html( // Remove whitespaces & Create our SPAN elements
    $(this).data("value").replace(/\s/g, "").replace(/[^,]+/g, function(m) {
      return "<span style='background:"+ m +";'>"+ m +"</span>";
    })
  ); 
}

function removeColorTokens() {
  $(this).text( $(this).data("value") );
}

function storeDataValue() {
  $(this).data("value", $.trim($(this).text()));
}

$("[contenteditable]").on({
  input    : storeDataValue,    // update data-value on input
  keypress : function(e) { return e.which !== 13; }, // Prevent Enter key
  focus    : removeColorTokens, // decolorify on focus
  blur     : toColorTokens      // colorify on blur
  
}).trigger("blur");             // Do it now!
[contenteditable]{
  border:1px solid #ddd;
  padding:4px 8px;
  border-radius:3px;
}
[contenteditable]:empty:not(:focus):before{
  content:attr(data-placeholder);
  color:#888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable data-value="red,green,blue,#F00BA4" data-placeholder="Enter tags"></div>