2016-05-15 25 views
4

我在表单中有一个令牌输入,所以我希望每个逗号分隔的令牌具有不同的颜色背景。我的问题是,如何按值创建每个元素,或者可以在值中使用id?如何为输入元素的文本颜色

我想

  • 红用红色背景,
  • 蓝用蓝色背景,
  • 绿色用绿色的背景,

我该怎么办完成这个?这里是我的代码:(!这是文字,你需要真正的子元素)

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

你可以使用一些jQuery插件如jquery tagit。它会照顾分离标签,会给你更多的选择,如通过点击关闭按钮来删除任何标签,也可以任何你想要的样式。 –

回答

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>

+1

伟大的解决方法! Upvoted当然 – dippas

+0

谢谢队友! @dippas –

+0

伟大的解决方法,但我需要丰富多彩的Tokeninput,这是源 http://sliptree.github.io/bootstrap-tokenfield/ 所以每个令牌有不同的背景,你知道热吗? –

相关问题