【问题标题】:Textarea selection in IE 11 not working appropriately on last lineIE 11 中的文本区域选择在最后一行无法正常工作
【发布时间】:2016-10-12 14:31:17
【问题描述】:

我正在构建一个 Angular 指令,该指令由一个用于编写 Markdown 的文本区域和将格式插入文本区域的按钮组成。单击时,如果当前未选择任何文本,则按钮(例如粗体)应附加以下内容:

**replace text**

选择了替换文本

它在每种方案中都在预期工作,保存以下内容:在IE 11中,当在最终行上发生选择时,但不是第一行。它在所有其他浏览器中都可以正常工作,并且在 IE 11 中也可以正常工作,但不存在这种情况。

这是指令中用于执行选择的代码:

var editor = element.find('textarea')[0];

function createWrappingMarkdown(symbol) {

    // If text is selected, wrap that text in the provided symbol
    // After doing so, set the cursor at the end of the highlight, 
    // but before the ending symbol(s)

    /* This section works fine */

    if (editor.selectionStart < editor.selectionEnd) {
        var start = editor.selectionStart,
            end = editor.selectionEnd;

        var value = editor.value.substring(0, start) + symbol +
            editor.value.substring(start, end) + symbol +
            editor.value.substring(end, editor.value.length);

        scope.$evalAsync(function () {
            editor.value = value;
            editor.focus();
            editor.selectionStart = end + symbol.length;
            editor.selectionEnd = end + symbol.length;
        });

    // If no text is highlighted, insert {symbol}replace text{symbol} 
    // at the current cursor position.
    // After inserting, select the text "replace text"

    /* This is where the selection is broken in IE 11 */

    } else if (editor.selectionStart || editor.selectionStart === 0) {
        var start = editor.selectionStart,
            message = "replace text";

        var value = editor.value.substring(0, start) + symbol +
            message + symbol + editor.value.substring(start, editor.value.length);

        scope.$evalAsync(function () {
            editor.value = value;
            setCursorSelect(start + symbol.length, start + symbol.length + message.length);
        });
    }
}

function setCursorSelect(start, end) {
    editor.focus();
    if (editor.setSelectionRange) {
        editor.setSelectionRange(start, end);
    } else {
        editor.selectionStart = start;
        editor.selectionEnd = end;
    }
}

更新

请参阅有关此问题的解决方法的答案。 Plunk 已被修改以演示此修复。

【问题讨论】:

    标签: javascript angularjs internet-explorer


    【解决方案1】:

    在 IE 中进一步调试后,我发现每当光标位于文本区域中的最后一个可用位置时,editor.selectionStart 被设置为高于editor.value.length 的值。这仅发生在 IE 中,而不是其他浏览器。考虑到这一点,只要按下按钮后需要进行选择,我就能够提出以下解决方案:

    scope.$evalAsync(function () {
        if (editor.value.length < editor.selectionStart) {
            start = editor.value.length;
        }
    
        editor.value = value;
        setCursorSelect(start + symbol.length, start + symbol.length + message.length);
    });
    

    上面的 plunk 已更新以反映此修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-11
      • 2014-08-17
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多