问题
I am making a text editor for my blogging website. I want to give users a small tool box where they could edit their blog post by selecting the text and applying some styling, like making the selected text bold or italic or giving the selected text some color. Also options for inserting images, and video links.
I searched SO but could not get any satisfactory solution.
It would be great if anyone can help me finding the caret position for selection( or without selection). I tried the jQuery caret pluggin but its not working.
my code looks like this ( arrived at this reading a post on SO only ):
HTML:
<div id="editor" contentEditable="true">
Initial text...
</div>
In a separate JS file:
(function(){
$("#editor").bind("keydown keypress mousemove", function() {
alert("Current position: " + $(this).caret().start);
});
}());
I am getting the following error in firebug when the page loads and nothing happens on keypress or any event:
it says
f.value is undefined
I also tried this link
but the solution provided here wont work if there is any other tag inside the original div.
Please help. Also if you have some better possible solutions or totally different approach, guide me.
回答1:
The jQuery caret plug-in (I assume you mean this one) is only for text inputs and textareas. Contenteditable elements work very differently, so that's why it isn't working.
If you want the caret position or selection in terms of character offsets, my answer here may help, although generally for what it sounds like you're trying to do, these numbers won't be very helpful. It sounds to me as though you need to be looking at document.execCommand().
来源:https://stackoverflow.com/questions/10414654/how-to-get-caret-position-for-contenteditable-div