简体   繁体   English

ContentEditable Div中的Javascript Set插入符号

[英]Javascript Set Caret in ContentEditable Div

I have a div tag that is contenteditable so that users can type in the div. 我有一个内容可编辑的div标签,以便用户可以输入div。 There is a function that adds a link into the div when the user presses a button. 有一个功能可以在用户按下按钮时将链接添加到div中。 I would like the caret to be positioned after the link so that users can continue to type. 我希望将插入符号放置在链接之后,以便用户可以继续输入。 The link can be inserted many times. 该链接可以插入多次。

Example Code: 示例代码:

<div id="mydiv" contenteditable="true" tabindex="-1">before <a href="#">link</a> after</div>

I require this code to work in: IE, Firefox, Opera, Safari and Chrome. 我需要以下代码才能在IE,Firefox,Opera,Safari和Chrome中使用。

Can anyone offer any help? 谁能提供任何帮助?

Assuming you have a reference to the <a> element you've inserted in a variable called link : 假设您引用了插入到名为link的变量中的<a>元素:

function setCaretAfter(el) {
    var sel, range;
    if (window.getSelection && document.createRange) {
        range = document.createRange();
        range.setStartAfter(el);
        range.collapse(true);
        sel = window.getSelection(); 
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(el);
        range.collapse(false);
        range.select();
    }
}

setCaretAfter(link);

I looked inside the CKEditor (http://ckeditor.com/) code and found that it has an appendBogus() function as well as inserts an extra <br><span> </span></br> that is then deleted. 我查看了CKEditor(http://ckeditor.com/)代码,发现它具有appendBogus()函数,并插入了一个额外的<br> <span> </ span> </br>,然后将其删除。

The problem of course is that Gecko/IE browsers also have nuances about how <br> tags work too (ie whether to use \\r or \\n to insert into the range vs. adding an <br> element) 当然,问题在于Gecko / IE浏览器还对<br>标记的工作方式也有细微差别(即,是否使用\\ r或\\ n插入范围,而不是添加<br>元素)

You can read through the _source/plugins/enterkey/plugin.js to see the different nuances with handling IE & Gecko. 您可以阅读_source / plugins / enterkey / plugin.js,以了解处理IE和Gecko时的细微差别。 It seems like one big hack... 似乎是一个大黑客...

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

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