execCommand适用于当前选择。当你点击按钮(实际上,你的textinput以外的任何地方),你取消选择当前选定的文本。此代码的目的是恢复您的contentEditable的选择。如果当前没有选择任何内容,则也是如此,则至少需要还原插入位置(这是长度为0个字符的选择)。
首先,你需要每一个用户改变了选择时间存储选择的范围(在我的情况下,KEYUP和MouseUp):
this.textInput.onmouseup = this.textInput.onkeyup = function(){
this.updateSelection();
this.updateStatus();
}.bind(this);
存储的选择范围中为该目的数组:
this.updateSelection = function(){
this.selection = [];
var sel = this.getSelection();
for(var i=0; i<sel.rangeCount; i++)
this.selection.push(sel.getRangeAt(i).cloneRange());
};
并执行该命令,恢复选择之前:
this.reselect = function(){
var sel = this.getSelection();
sel.removeAllRanges();
for(var i=0; i<this.selection.length; i++)
sel.addRange(this.selection[i].cloneRange());
};
this.reselect();
document.execCommand("bold");
this.getSelection
被定义为(但无可否认有点粗鲁):
return window.getSelection ? window.getSelection() :
(document.getSelection ? document.getSelection() :
document.documentElement.getSelection());
我假设你有一个CONTENTEDITABLE,不仅仅是一个简单的文本区域。
来源
2017-03-06 11:44:47
Psi
对不起,我还是不太明白,如果你能介意说明一下吗? –
更新我的答案 – Psi
感谢您的回复,而不是使用contentEditable,而是最终使用了iframe。 –