Div Editable and More… More

旧巷老猫 提交于 2019-12-23 02:34:44

问题


Well,

I need to replace a word, in a div contentEdible property on, by the same word but formatted...
Like this:
<div> My balls are big </div>

To this (replace the word: balls):
<div> My <font style="color:blue;">balls</font> are big </div>

In a contentEditable this happens dinamically, while the user type the text the replacements happens. I think that a simple event onkeydown, onkeyup, or onkey press, can solve this part. But, the trouble is with the caret, that after all that i tryed, it stay before the word replaced, when should be stay after. I tryed write some js code, tryed find some jquery scripts, but all them failed in this situation...

Any one has some ideia, or trick ?

I think: --> Record the length of the word unformatted. --> Delete this word --> Put new word formatted. --> Walk with the caret, to position based this formatted word length. --> Is it? PS: I have to considerate a word in any place of this div.

I don't know how to write this code that do what i say above.

Correct me, if i'm wrong.

Since yet, thanks!

Edit[1]: I want that this works on Mozilla Firefox, specificlly;


回答1:


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(); 
    }   
}


来源:https://stackoverflow.com/questions/3366321/div-editable-and-more-more

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!