javascript - 命令值的事件监听器

标签 javascript html reactjs dom-events contenteditable

我已经使用 contenteditable 构建了一个富文本编辑器,并且有一个按钮可以通过执行 document.execCommand("bold") 使文本变为粗体。当此命令处于事件状态时,我想以不同的方式设置按钮的样式(这意味着我写的下一个字符将变为粗体)。一个 hack 是过度检查 document.queryCommandValue("bold"),但我希望有更好的解决方案。

有什么方法可以监听 document.queryCommandValue("bold") 的值发生变化吗?

最佳答案

您可以检查插入符号位置的计算样式并相应地更新您的按钮:

// 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

关于javascript - 命令值的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49500777/

相关文章:

javascript - PhantomJS;使用 Java 单击元素

javascript - 解析 iOS、云代码和后台作业

javascript - React Native 交错渲染

html - 在 HTML 中明确设置禁用 ="false"不起作用

javascript - React Router - 单击后删除链接组件?

javascript - React 组件如何一次渲染一个而不嵌套在其父级的渲染中?

javascript - 如何正确地从我的 Controller 返回注释并在 .done() AJAX 函数中使用它?

javascript - 使用 'findOne' 或 'findAll' 后 Sequelize 不会更新

html - 介绍页面中的响应式图像和视频

html - 如何使用django在所有浏览器中播放wav文件?