在满足div内的span元素后设置光标 [英] Set cursor after span element inside contenteditable div

查看:1178
本文介绍了在满足div内的span元素后设置光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在contenteditable div内的span元素后面设置光标?
现在,我在span元素中有一个图像,在contenteditable div内。



当我添加一些字符时,它们被添加到span中,但我希望它们在span元素之后添加。任何想法如何实现这一点?

解决方案

在IE <8以外的浏览器中, p>

  function placeCaretAfterNode(node){
if(typeof window.getSelection!=undefined){
var range = document.createRange();
range.setStartAfter(node);
range.collapse(true);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);






$ b然而,一些浏览器(特别是基于WebKit的浏览器)对文档中哪些位置对插入符号有效有一定的认识,并且将对添加到选择中的任何范围进行标准化以符合这些想法。以下示例将在Firefox和IE 9中执行您想要的操作,但不会在Chrome或Safari中执行此操作:

http://jsfiddle.net/5dxwx/



所有解决方法都不错。选项包括:


  • 在范围后添加一个零宽度空格字符并将其选中使用
  • 一个< a> 元素而不是< span> ,因为WebKit会为< a> 元素


How can I set the cursor after a span element inside an contenteditable div? Right now, I've an image inside a span element, inside the contenteditable div.

When I add some characters, they are added inside the span, but I want them to be added after the span element. Any ideas how I can achieve this?

解决方案

In browsers other than IE <= 8, this will do it:

function placeCaretAfterNode(node) {
    if (typeof window.getSelection != "undefined") {
        var range = document.createRange();
        range.setStartAfter(node);
        range.collapse(true);
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

However, some browsers (notably WebKit-based ones) have fixed ideas about which positions in the document are valid for the caret and will normalize any range you add to the selection to comply with those ideas. The following example will do what you want in Firefox and IE 9 but not in Chrome or Safari as a result:

http://jsfiddle.net/5dxwx/

None of the workarounds are good. Options include:

  • add a zero-width space character after the span and select it
  • use an <a> element instead of a <span> because WebKit makes an exception for <a> elements

这篇关于在满足div内的span元素后设置光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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