Textarea使用Javascript切换选择标签 [英] Textarea toggle selection tags with Javascript

查看:106
本文介绍了Textarea使用Javascript切换选择标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

示例:

文本区域

Lorem ipsum dolor sit amet.

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

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

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

谢谢!

解决方案

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

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

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!

解决方案

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

这篇关于Textarea使用Javascript切换选择标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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