Div的“内容可编辑" :获取和删除插入符号前的单词 [英] Div "contenteditable" : get and delete word preceding caret

查看:135
本文介绍了Div的“内容可编辑" :获取和删除插入符号前的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢这个问题和蒂姆(Tim)发布的答案向下,我创建了一个函数,以在"contenteditable" div中的插入符号前得到该词.

Thanks to this question and answer posted by Tim Down, I made a function to get the word preceding caret in a "contenteditable" div.

这是一个小提琴,这里是函数:

Here's a fiddle, and here's the function:

function getWordPrecedingCaret (containerEl) {
    var preceding = "",
        sel,
        range,
        precedingRange;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            range = sel.getRangeAt(0).cloneRange();
            range.collapse(true);
            range.setStart(containerEl, 0);
            preceding = range.toString();
        }
    } else if ((sel = document.selection) && sel.type != "Control") {
        range = sel.createRange();
        precedingRange = range.duplicate();
        precedingRange.moveToElementText(containerEl);
        precedingRange.setEndPoint("EndToStart", range);
        preceding = precedingRange.text;
    }
    var lastWord = preceding.match(/(?:\s|^)([\S]+)$/i);
    if (lastWord) {
        return lastWord;
    } else {
        return false;
    }
}

我的问题:拿到最后一个字后,如何将其从div中删除?请注意,我不想删除div中该单词的任何出现,只希望删除插入符号之前的出现.

My question: Once gotten the last word, how can I remove it from the div? Note that I don't want to remove any occurrence of the word in the div, only occurrence preceding the caret.

提前谢谢!

推荐答案

您可以尝试使用index属性/Reference/Global_Objects/String/match"rel =" nofollow> match()

You could try using index property of match()

var lastWordPosition = preceding.match(/(?:\s|^)([\S]+)$/i).index;

然后您可以执行substring(0, lastWordPosition)或任何您想执行的操作...

Then you can do a substring(0, lastWordPosition) or whatever you want…

这篇关于Div的“内容可编辑" :获取和删除插入符号前的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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