我正在构建一个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进行了修改,以演示此修复程序。
在IE中进一步调试之后,我发现该editor.selectionStart
值被设置为高于editor.value.length
光标位于textarea中最后一个可用位置时的值。这仅在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);
});
上面的代码已更新,以反映此修复程序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句