简体   繁体   中英

hHow to get caret position for contentEditable div?

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 Stack Overflow 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 plugin but its not working.

My code looks like this (arrived at this reading a post on Stack Overflow 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.

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() .

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