如何找到光标所在的Word

时间:2009-04-24 23:55:01

标签: javascript textarea cursor

如何在IE中检测光标所在的单词? 我试过这段代码:

window.setInterval(function () {
    var range = document.selection.createRange();
    range.expand('word');
    var wort = range.text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    document.getElementById("ausgabe").innerHTML = wort;
}, 100)
<textarea id="ta" rows="10" cols="40">At vero eos et accu-samus et iusto? Odio, dignissimos. ducimus qui bländitiis praeséntium voluptatèm deleniti atque corrupti quos</textarea>
<p>[<span id="ausgabe"></span>]</p>

但是当我将光标设置在Textarea的开头和结尾时会出现问题。它给了我完整的文字。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我确信有更好的方法可以解决这个问题,所以我希望其他人也会对这个问题有所了解。这个解决方案使用一些试验和错误来移动范围 - 如果出现问题,它将恢复到原始状态。

我希望这有帮助!

以下是代码:

<html>
<body>
<script>
    window.setInterval(
        function () {
            var selection = document.selection;
            var range = document.selection.createRange();

            var parentEl = range.parentElement();

            // Make a duplicate range to revert to if things go wrong.
            range2 = range.duplicate();

            range.moveStart('character', 1);
            if (range.parentElement() != parentEl) {
                // We've left the original parent (which is bad), so revert to the original range. We're probably at the end of the textarea.
                range = range2.duplicate();
            }
            range.moveStart('word', -1);

            // Make a new duplicate range to revert to.
            range2 = range.duplicate();

            // Move the end of the range one backwards, then forward to the end of the word.
            range.moveEnd('character', -1);
            range.moveEnd('word', 1);
            if (range.parentElement() != parentEl) {
                range = range2.duplicate();
                while (range2.parentElement() == parentEl) {
                    range.moveEnd('character', 1);
                    range2 = range.duplicate();
                }
            }

            var wort = range.text.replace(/^\s\s*$/, '').replace(/\s\s*$/, '');
            document.getElementById("ausgabe").innerHTML = wort;
        }, 100
    )
</script>

    <textarea id="ta" rows="10" cols="40">At vero eos et accu-samus et iusto? Odio, dignissimos. ducimus qui bländitiis praeséntium voluptatèm deleniti atque corrupti quos</textarea>

<p>[<span id="ausgabe"></span>]</p>
</body>
</html>