我正在我的网站上开发一个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/
在此先感谢您的帮助.
解决方法
我喜欢这个问题,我很努力地解决.我相信我终于成功了(有一点帮助).
= UPDATED =
代码:
- [...]
- // 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