如何获得contentEditable div的插入符位置? [英] how to get caret position for contentEditable div?

查看:137
本文介绍了如何获得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.

我搜索了SO,但没有任何令人满意的解决方案。

I searched SO but could not get any satisfactory solution.

如果有人能帮助我找到插入标记的位置以供选择(或不进行选择),那将是很好的。我尝试了jQuery插入符插件,但无法正常工作。

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.

我的代码如下所示(此文章仅针对SO撰写):

my code looks like this ( arrived at this reading a post on SO only ):

HTML:

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

在另一个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:

它说


f。值未定义

f.value is undefined

我也尝试过该链接

,但如果原始div中还有其他标签,则此处提供的解决方案将无法正常工作。

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.

推荐答案

jQuery插入符号(我假设您的意思是)仅适用于文本输入和文本区域。可内容编辑的元素的工作方式大不相同,因此这就是为什么它不起作用的原因。

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.

如果您想要插入符的位置或选择的字符偏移量,请我在这里的答案可能会有所帮助,尽管通常来说,听起来像是您要尝试做的事情,但这些数字并不会很有帮助。在我看来,您好像需要查看 文档。 execCommand()

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

这篇关于如何获得contentEditable div的插入符位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆