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

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

我搜索了Stack Overflow,但找不到任何令人满意的解决方案.

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

我的代码看起来像这样(仅在阅读有关Stack Overflow的帖子时才到达):

My code looks like this (arrived at this reading a post on Stack Overflow only):

HTML:

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

在单独的JS文件中:

(function(){
$("#editor").bind("keydown keypress mousemove", function() {
        alert("Current position: " + $(this).caret().start);
    });
}());

当页面加载且按键或任何事件均未发生任何事情时,我在Firebug中收到以下错误:

I am getting the following error in Firebug when the page loads and nothing happens on keypress or any event:

它说:

f.value未定义

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.

如果您想要插入符的位置或选择字符偏移量,虽然通常适用于此处我的回答可能会有所帮助.听起来像是您要尝试做的事情,这些数字并不会很有帮助.在我看来,您好像需要查看 document.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().

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

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