我正在我的网站上开发一个 contentEditable 区域,用户可以在其中互相输入消息。
<div contentEditable="true" class="smartText">User types here...</div>
事情是,我们将在里面有智能文本,这意味着如果用户在这个 div 中键入 @usersame
,如果 @username
应该以蓝色突出显示用户名存在,如果他不存在则为绿色。当然,所有这一切都应该在用户输入时发生......
我不知道从哪里开始,现在我有这个:
$("body").on("keyup",".smartText",function(){
var $this = $(this),
value = $this.html(),
regex = /[^>]#\S+[^ ]/gim;
value = value.replace(regex,"<span style='color:red'>$&</span>");
$this.html(value);
});
但是文本一直在跳动(以及插入符号的位置)并且感觉方向不对。我想它有点类似于 JSFiddle,它会在找到它时为代码着色。 我基本上想要和 Twitter 一样的东西。
这是一个可以玩的 JSFiddle:http://jsfiddle.net/denislexic/bhu9N/4/
预先感谢您的帮助。
最佳答案
我喜欢这个问题,并且非常努力地解决了这个问题。我相信我终于成功了(在一些帮助下)。
= 已更新 =
一段代码:
[...]
// formatText
formatText: function (el) {
var savedSel = helper.saveSelection(el);
el.innerHTML = el.innerHTML.replace(/<span[\s\S]*?>([\s\S]*?)<\/span>/g,"$1");
el.innerHTML = el.innerHTML.replace(/(@[^\s<\.]+)/g, helper.highlight);
// Restore the original selection
helper.restoreSelection(el, savedSel);
}
[...]
// point
keyup: function(e){
// format if key is valid
if(helper.keyIsAvailable(e)){
helper.formatText($this[0]);
}
// delete blank html elements
if(helper.keyIsDelete && $this.text()=="") {
$this.html("");
}
}
截图:
JSFiddle 在这里: http://jsfiddle.net/hayatbiralem/9Z3Rg/11/
需要的外部资源:
- http://dl.dropboxusercontent.com/u/14243582/jscalc/js/rangy-core.js
- http://dl.dropboxusercontent.com/u/14243582/jscalc/js/rangy-selectionsaverestore.js
帮助问题(感谢): replace innerHTML in contenteditable div
正则表达式测试工具(感谢): http://www.pagecolumn.com/tool/regtest.htm
关于javascript - Jquery/Javascript - 在 contentEditable 区域中作为用户类型突出显示的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13107150/