multiple contenteditable elements, using arrow keys to navigate
I got multiple 开发者_运维问答<p contenteditable="true"></p>
elements on a page. I'm looking for a solution to use arrow keys for navigating across those disjoint elements just as if they were one single editable element.
So for instance, if the caret is at the 10th character on the last line of the 1st paragraph and the user hits the down arrow key, the caret should jump to the 2nd paragraph and place the caret at the 10th character (if there's one) on its first line.
Appreciate any comments.
Revised answer
You can detect that the caret is at the start or end of the current editable element by using something like the following (example is for down array on the last line):
- Detect the down arrow
keydown
event - Check if the caret is at the end of the paragraph by doing one of the following:
- Create a
Range
(orTextRange
in IE) from the selection object and comparing it to another Range that encompasses the whole paragraph. This is the slightly trickier but more seamless option. OR: - Store the selection and set a brief timer (say 1 millisecond) to allow the keypress to take effect. The function passed to the timer calls compares the current selection with the previously stored selection. If they're the same, the caret has not moved and must have been at the end of the paragraph.
- If the caret is at the end of the paragraoph, move it to the start of the next editable paragraph.
This isn't the the usual behaviour of the caret but is reasonably easy to achieve and could be a reasonable compromise. The problem is that there's no reliable cross-browser way to work out the caret's coordinates.
What if you would make the container element editable, instead of every single paragraph? For example:
<div contenteditable="true">
<p>Lorem ipsum</p>
<p>dolor sit</p>
</div>
精彩评论