Div Editable and More… More

杀马特。学长 韩版系。学妹 提交于 2019-12-08 15:24:32

I only have IE6/7 on this machine, but maybe you can apply the concept to other browser versions of Ranges (or maybe this is cross-browser?).

Basically we store the cursor position, make our search/replacement, then put the cursor back where it was:

html:

<div id="content" contentEditable="true" onkeyup="highlight(this)">This is some area to type.</div>

and the script:

function highlight(elem) {
// store cursor position
var cursorPos=document.selection.createRange().duplicate();
var clickx = cursorPos.getBoundingClientRect().left; 
var clicky = cursorPos.getBoundingClientRect().top; 
// copy contents of div
var content = elem.innerHTML;
var replaceStart = '<font style="color:blue">';
var replaceEnd = '</font>';
// only replace/move cursor if any matches
// note the spacebands - this prevents duplicates
if(content.match(/ test /)) {
    elem.innerHTML = content.replace(/ test /g,' '+replaceStart+'test'+replaceEnd+' ');
    // reset cursor and focus
    cursorPos = document.body.createTextRange();
    cursorPos.moveToPoint(clickx, clicky);
    cursorPos.select(); 
    }   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!