更改文本框输入颜色的一部分

时间:2014-04-01 15:47:15

标签: javascript jquery angularjs

我想知道是否可以只改变文本输入框颜色的一部分。我正在创建一个评论小部件,希望@和::之间的所有内容都改为不同的颜色:

<input type="text" placeholder="Want To Say Something?" 
value="@user556: This is a test comment" ng-model="Comment" ng-click="getCurrentPosition()" 
class="form-control ng-valid valid ng-dirty">

这可能与jQuery或javascript有关吗?或者我是否必须将文本输入转换为div?

1 个答案:

答案 0 :(得分:0)

可能在contenteditable元素内,
并使用一些JS和一些RegExp来替换所需的匹配:

&#13;
&#13;
function colorify() {
  this.innerHTML = this.textContent.replace(/@([^:]+):/g, "@<span class='user'>$1</span>:");
}

function uncolorify() {
  this.innerHTML = this.textContent;
}

[].forEach.call(document.querySelectorAll(".comment"), function(el){
  el.addEventListener("blur",    colorify);
  el.addEventListener("focus", uncolorify);
});
&#13;
[contenteditable] {
  background:#fafafa;
  padding:8px;
  border-radius:3px;
  border:1px solid #ddd;
}
[contentEditable]:empty:not(:focus):before {
  /*http://stackoverflow.com/a/18368720/383904*/
  content: attr(data-placeholder);
  color: #777;
}
.user{
  color: #f0f;
}
&#13;
(Copy the following text into the contenteditable)<br>
@user547794: Use contenteditable. @johnDoe: nice suggestion btw.
<div class="comment" contenteditable data-placeholder="Want To Say Something?"></div>
Than click outside of the contenteditable.
&#13;
&#13;
&#13;