我想知道是否可以仅更改文本输入框颜色的一部分。我正在创建一个评论小部件,希望 @ 和 : 之间的所有内容都更改为不同的颜色:
<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?
最佳答案
可能,在 contenteditable
元素内,
并用一些 JS 和一些 RegExp 来替换所需的匹配:
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);
});
[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;
}
(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.
关于javascript - 更改部分文本框输入的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22790723/