document.execCommand不能与addEventListener一起使用

时间:2018-04-04 03:34:59

标签: javascript dom

我目前正在制作HTML的可编辑部分。我正在使用document.execCommand方法,但是我无法使用addEventListener。但是,使用内联JavaScript它可以工作。这是不起作用的代码。

let btn = document.getElementById('click');

btn.addEventListener('click', function(){
 document.execCommand("bold")
 let a = document.execCommand("bold") ? true: false;
 console.log(a);
})

但是,如果我使用内联,它可以工作

<button id="click" onclick="document.execCommand("bold")">CLICK</button>

在addEventListener中调用document.execCommand方法的行为是否有所不同?

1 个答案:

答案 0 :(得分:0)

您遇到的问题是,如果添加或删除了粗体,则您希望使用布尔值。问题是the Boolean只是告诉您所选内容是否能够切换粗体。如果添加或删除它,它无关。

那么你能做些什么才能发现它呢?那么你可以查看当前选择中的内容并查看父元素是否为粗体。或者您可以使用似乎poorly documented everywhere的方法queryCommandState,它允许您查看当前选择的状态。将其与选择更改事件相结合,您可以确定它是否已应用。

基本理念:

&#13;
&#13;
var btnBold = document.querySelector("button")
btnBold.addEventListener("mousedown", function (evt) {
  evt.preventDefault();
  var x = document.execCommand("bold");
  console.log(document.queryCommandState('bold'));
})

document.addEventListener("selectionchange", function (evt) {
  btnBold.classList.toggle("active", document.queryCommandState('bold'));
})
&#13;
div { outline: 1px solid black; }
button.active { background-color: green; }
&#13;
<div id="x" contenteditable="true">
 Foo Bar
</div>
<button>Bold</button>
&#13;
&#13;
&#13;

相关问题