如何获取所选文本输入的前后

How to get the before and after of selected text input

我正在尝试在 Jquery 中实现 BoldItalic 并带有星号和下划线(就像在 whatsapp 中一样)。通过使用 Madapaja's Selection Library,我可以添加星号或下划线,但我不知道如何删除所选文本前后存在的星号或下划线。我知道有重复的问题,但我想通过使用该库来实现这一点,因为它具有跨浏览器支持。

我是这样加星的:

$(document).ready(function () {
    $('#boldButton').click(function () {

        var selection = $("#inputQuestion").selection();

        if (selection.trim()) {//not empty or not whitespace
            $('#inputQuestion')
            .selection('insert', { text: '*', mode: 'before' })
            .selection('insert', { text: '*', mode: 'after' });
        }
    });
});

到这个html:

<button id="boldButton" type="button" class="btn btn-default"><b>B</b></button>
<textarea class="form-control" rows="10" id="inputQuestion"></textarea>

您可以检查 wiki and the source code

任何帮助或任何其他方法将不胜感激!

更新: 通过dpren的回答,我是这样实现的:

$(document).ready(function () {
    $('#boldButton').click(function () {

        var selection = $("#inputQuestion").selection();
        var selectedPos = $("#inputQuestion").selection('getPos');

        if (selection.trim()) {//not empty or not whitespace
            var before = $('#inputQuestion')
                .selection('setPos', { start: selectedPos.start - 1, end: selectedPos.start })
                .selection();

            var after = $('#inputQuestion')
                .selection('setPos', { start: selectedPos.end, end: selectedPos.end + 1 })
                .selection();

            if (before == '*' && after == '*') { //already bold -> remove stars
                var before = $('#inputQuestion')
                    .selection('setPos', { start: selectedPos.start - 1, end: selectedPos.start })
                    .selection();

                $('#inputQuestion').selection('replace', { text: '' });

                var after = $('#inputSoru') //since we remove 'before', positions will decrese by one
                    .selection('setPos', { start: selectedPos.end-1, end: selectedPos.end })
                    .selection();

                $('#inputSoru').selection('replace', { text: ''});

            } else { // not bold -> make it bold
                $('#inputQuestion') //get back to user's selection
                .selection('setPos', { start: selectedPos.start, end: selectedPos.end })
                .selection();

                $('#inputSoru')
                    .selection('insert', { text: '*', mode: 'before' })
                    .selection('insert', { text: '*', mode: 'after' });
            }
        }
    });
});

不过,我觉得这段代码有重复。有没有办法通过编辑选择库来实现?

您的整体解析问题可能有更简单的解决方案,但对于您的直接问题,您可以在插入操作后使用 getPossetPos 来扩展您的选择。

var position = $('#inputQuestion')
    .selection('insert', { text: '*', mode: 'before' })
    .selection('insert', { text: '*', mode: 'after' })
    .selection('getPos');

var newSelection = $('#inputQuestion')
    .selection('setPos', {start: position.start - 1, end: position.end + 1})
    .selection();

JSFiddle demo