JavaScript在游标之前获取单词 [英] JavaScript get word before cursor

查看:148
本文介绍了JavaScript在游标之前获取单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我一直在网上找到一个解决方案,但我找不到一个,是有一种方法,在一个可编辑的div中的插入位置之前得到这个词,有点像:

Okay, I've been looking all over the web to find a solution but I couldn't find one, is there a way to get the word before the caret position in an editable div so a bit like:

This is some| demo texts

这应该返回单词some...我不知道这是否。

This should return the word "some"... I don't know if this is possible, I would be glad for any help, thanks :).

推荐答案

使用提供的插入点位置查找器方法这里这将做你想要的。

With using Caret Position finder method provided here this will do what you want.

    function GetCaretPosition(ctrl) {
        var CaretPos = 0;   // IE Support
        if (document.selection) {
            ctrl.focus();
            var Sel = document.selection.createRange();
            Sel.moveStart('character', -ctrl.value.length);
            CaretPos = Sel.text.length;
        }
        // Firefox support
        else if (ctrl.selectionStart || ctrl.selectionStart == '0')
            CaretPos = ctrl.selectionStart;
        return (CaretPos);
    }

    function ReturnWord(text, caretPos) {
        var index = text.indexOf(caretPos);
        var preText = text.substring(0, caretPos);
        if (preText.indexOf(" ") > 0) {
            var words = preText.split(" ");
            return words[words.length - 1]; //return last word
        }
        else {
            return preText;
        }
    }

    function AlertPrevWord() {
        var text = document.getElementById("textArea");
        var caretPos = GetCaretPosition(text)
        var word = ReturnWord(text.value, caretPos);
        if (word != null) {
            alert(word);
        }
    }

实施

<input id="textArea" type="text" />
<br />
<input id="Submit" type="submit" value="Test" onclick="AlertPrevWord()" />

http://jsfiddle.net/arrwP/2/

这篇关于JavaScript在游标之前获取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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