简体   繁体   中英

Google Chrome moves cursor to end of the previous node when setting it to the start of a node with JavaScript

I have the following content in a TinyMCE instance:

<p><span id="span1">Test</span><span id="span2">Bla</span></p>

When the user sets the cursor before the “B” and starts typing, I want the text to be typed into the second span. Google Chrome (I am using Chromium 11.0.696.65 to be exact) sets the cursor to the end of the first span, which you can verify using the following code:

document.body.innerHTML = '<p><span id="span1">Test</span><span id="span2">Bla</span></p>';
document.designMode = "on";
// Now click between the “t” and the “B”
var sel = document.getSelection();
alert(sel.baseNode.data);

Unfortunately, it does not seem to be possible to set the focus to the beginning of the second span manually:

var span = document.getElementById("span2");
sel.setBaseAndExtent(span, 0, span, 0);
alert(sel.baseNode.data); // Is still “Test”!
sel.setBaseAndExtent(span, 1, span, 1); // Move inside the span for testing
alert(sel.baseNode.data); // Now it’s “Bla”…

Google Chrome seems to move the cursor to the end of the previous node again. I have also tried to modify the Range object instead, but this resulted in the same problem.

I can't think of any solution to this problem, does anyone have an idea what is causing this and how to fix it?

Cheers,
Candid

This is a long-standing bug in WebKit that has been frustrating rich text editor developers for years. Relevant WebKit bugs:

There isn't a decent solution, unfortunately. I have in the past resorted to tracking the cursor position, inserting a zero-width space character at the start of the current text node and removing it later once the cursor has gone elsewhere, but that's an absolute pain to manage and is difficult to get right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM