我正在构建一个Angular指令,该指令由用于编写Markdown的textarea和用于在文本区域中插入格式的按钮组成。单击时,如果当前未选择任何文本,则按钮(例如,粗体)应附加以下内容:
**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已经过修订,以证明此修复程序。
答案 0 :(得分:0)
在IE中进一步调试之后,每当光标位于textarea中的最后一个可用位置时,我发现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);
});
上面的插件已更新以反映此修复程序。