【问题标题】:Event listener for command value命令值的事件监听器
【发布时间】:2018-03-26 21:18:54
【问题描述】:
我使用contenteditable 构建了一个富文本编辑器,并有一个通过执行document.execCommand("bold") 使文本变为粗体的按钮。当此命令处于活动状态时,我想为按钮设置不同的样式(这意味着我写的下一个字符将是粗体)。一个技巧是过度检查document.queryCommandValue("bold"),但我希望有更好的解决方案。
document.queryCommandValue("bold")的值发生变化时有什么方法可以监听吗?
【问题讨论】:
标签:
javascript
html
reactjs
dom-events
contenteditable
【解决方案1】:
您可以检查插入符号位置的计算样式并相应地更新您的按钮:
// Get your contenteditable
var my_editor = document.getElementById("my_editor");
// Declare the function to update your buttons
function update() {
// getting style at caret position
var sel = window.getSelection();
var style = sel.focusNode && window.getComputedStyle(sel.focusNode.parentElement);
// guessing if text is bold
var fW = style.fontWeight;
var is_bold = fW && (parseInt(fW) > 400 || fW.indexOf("bold") == 0);
// updating your buttons accordingly
}
// Bind the function to useful events
my_editor.addEventListener("input", update); // when content is modified
my_editor.addEventListener("click", update); // when caret is changed with the mouse
my_editor.addEventListener("keyup", update); // when caret is changed with the keyboard arrows