使用 Javascript 的文本区域切换选择标签

发布于 2025-01-05 10:15:38 字数 312 浏览 0 评论 0原文

我正在开发 BBcode 编辑器,并且想知道如何使用 Javascript 在选择上切换标签(类似于 StackOverflow 上文本编辑菜单的工作方式)。

示例:

Textarea

Lorem ipsum dolor sit amet.

如果您选择文本“ipsum dolor”并单击粗体按钮,它将变为

Lorem [b]ipsum dolor[/b] sit amet.

如果您再次单击粗体按钮,它将删除标签。

谢谢!

I'm working on a BBcode editor, and was wondering how to toggle tags on selection using Javascript (similar to how the text editing menu works on StackOverflow).

Example:

Textarea

Lorem ipsum dolor sit amet.

If you select the text 'ipsum dolor' and click on the bold button, it'll become

Lorem [b]ipsum dolor[/b] sit amet.

If you click the bold button once again, it'll remove the tags.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪化雨蝶 2025-01-12 10:15:38

您可以获取选定的文本插入符号位置,设置插入符号,然后插入文本:

TL;DS(太长没有滚动)

底部有一个 TL;DR。

获取插入符位置

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 setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

插入文本

function insertTextAtCaret(el, text) {
    var pos = getSelectionBoundary(el, false);
    var newPos = pos + text.length;
    var val = el.value;
    el.value = val.slice(0, pos) + text + val.slice(pos);
    setSelection(el, newPos, newPos);
}

进行插入

var pos = getInputSelection($('#textboxID'));
setCaretPosition($('#textboxID'), pos.start);
insertTextAtCaret($('#textboxID'), '[b]');
setCaretPosition($('#textboxID'), pos.end);
insertTextAtCaret($('#textboxID'), '[/b]');

然后要撤消它,只需在单击按钮时检查文本选择,以及它是否包含在您单击的内容中(例如 [b]...[/b],当单击 B 按钮)然后从文本框选择中删除该文本。

TL;DR

获取一个 Markdown 插件 http://markitup.jaysalvat.com/home/

或查看在这些 http://www.queness.com/post/212/10-jquery-and-non-jquery-javascript-rich-text-editors

You can get the selected text caret positions, set the caret and then insert your text:

TL;DS (Too long didn't scroll)

There's a TL;DR at the bottom.

Get Caret Positions

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
    };
}

Set Caret Position

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

Insert Text

function insertTextAtCaret(el, text) {
    var pos = getSelectionBoundary(el, false);
    var newPos = pos + text.length;
    var val = el.value;
    el.value = val.slice(0, pos) + text + val.slice(pos);
    setSelection(el, newPos, newPos);
}

Do Your Inserting

var pos = getInputSelection($('#textboxID'));
setCaretPosition($('#textboxID'), pos.start);
insertTextAtCaret($('#textboxID'), '[b]');
setCaretPosition($('#textboxID'), pos.end);
insertTextAtCaret($('#textboxID'), '[/b]');

Then to undo it, just check the text selection when they click the button, and if its wrapped in the thing you clicked (eg [b]...[/b], when clicking the B button) then just remove that text from the textbox selection.

TL;DR

Get a markdown plugin instead http://markitup.jaysalvat.com/home/

or look at these http://www.queness.com/post/212/10-jquery-and-non-jquery-javascript-rich-text-editors

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文