I have a div tag that is contenteditable so that users can type in the div. If a user selects some text to make it bold, the following code is executed:
browser.execute("document.execCommand(\"Bold\");
document.getElementById(\"EditDIV\").focus()");
After the execution, the focus is lost and the vertical scrollbar in the browser moves to the top of the browser. I want the cursor to stay at the text where it was before.
I tried the following:
Store the selection position x, y:
Code:
cursorPos=document.selection.createRange().duplicate(); clickx = cursorPos.getBoundingClientRect().left; clicky = cursorPos.getBoundingClientRect().top;
Restore the selection position:
Code:
cursorPos = document.body.createTextRange(); cursorPos.moveToPoint(clickx, clicky); cursorPos.select();
But this code finds the position of the selected text with respect to the beginning of the current view in the browser. Hence, the cursor stay开发者_开发百科s at the same position but the text moves down.
It is expected to make the cursor stay at the text that was selected.
精彩评论