替换textarea中的选定文本 [英] Replacing selected text in the textarea

查看:139
本文介绍了替换textarea中的选定文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中执行此操作的最佳方法是什么?这应该是一个相当常见的用例。

what is the best way to do this in jQuery? This should be a fairly common use case.


  1. 用户选择textarea中的文本

  2. 他点击链接

  3. 链接中的文字替换textarea中的选定文本

任意代码将非常感激 - 我在第3部分遇到了一些问题。

Any code will be much appreciated - I am having some issues with part 3.

推荐答案

以下是你如何做到这一点,在所有专业浏览器。我还有一个包含此功能的 jQuery插件。有了它,代码将是

Here's how you can do it, in all major browsers. I've also got a jQuery plug-in that includes this functionality. With that, the code would be

$("your_textarea_id").replaceSelectedText("NEW TEXT");

这是一个完整的独立解决方案:

Here's a full stand-alone solution:

function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

function replaceSelectedText(el, text) {
    var sel = getInputSelection(el), val = el.value;
    el.value = val.slice(0, sel.start) + text + val.slice(sel.end);
}

var el = document.getElementById("your_textarea");
replaceSelectedText(el, "[NEW TEXT]");

这篇关于替换textarea中的选定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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