简体   繁体   English

h如何获得 contentEditable div 的插入符号位置?

[英]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.我搜索了 Stack Overflow,但没有得到任何满意的解决方案。

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.我尝试了 jQuery caret 插件,但它不起作用。

My code looks like this (arrived at this reading a post on Stack Overflow only):我的代码看起来像这样(仅在阅读 Stack Overflow 上的一篇文章时才到达这里):

HTML: HTML:

<div id="editor" contentEditable="true">
     Initial text...
</div>

In a separate JS file:在单独的 JS 文件中:

(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:当页面加载并且按键或任何事件没有任何反应时,我在 Firebug 中收到以下错误:

It says:它说:

f.value is undefined f.value 未定义

I also tried this link我也试过这个链接

but the solution provided here wont work if there is any other tag inside the original div.但是如果原始 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. jQuery caret 插件(我假设您指的是这个插件)仅用于文本输入和文本区域。 Contenteditable elements work very differently, so that's why it isn't working. Contenteditable 元素的工作方式非常不同,所以这就是它不起作用的原因。

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() .在我看来,您好像需要查看document.execCommand()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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