简体   繁体   English

document.execCommand无法与addEventListener一起使用

[英]document.execCommand wont work with addEventListener

I am currently working on an editable part of my HTML. 我目前正在处理HTML的可编辑部分。 I am using document.execCommand method, but however I can't get it to work with addEventListener. 我正在使用document.execCommand方法,但是我无法使其与addEventListener一起使用。 But, with inline javascript it work. 但是,使用内联JavaScript可以正常工作。 This is the code that don't work. 这是无效的代码。

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

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

But, If I use inline, it work 但是,如果我使用内联,它就可以工作

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

Does the document.execCommand method behave differently when invoked inside addEventListener? 在addEventListener内部调用时,document.execCommand方法的行为是否有所不同?

The problem you have is the fact you are expecting the Boolean to be if the bold was added or removed. 您遇到的问题是,如果添加或删除了粗体,您期望布尔值是。 Problem is the Boolean just tells you if what was selected was able to toggle bold. 问题是布尔值仅告诉您所选内容是否能够切换为粗体。 It has nothing to do if it was added or removed. 如果添加或删除它,则与它无关。

So what can you do to detect it? 那么,您该怎么做才能检测到它呢? Well you can look at what is in the current selection and see if a parent element is bold. 好了,您可以查看当前选择中的内容,并查看父元素是否为粗体。 Or you can use a method queryCommandState which seems to be poorly documented everywhere which allows you to see what the state of the current selection is. 或者,您可以使用方法queryCommandState ,该方法似乎在每个地方的文档都很少,它使您可以查看当前选择的状态。 Combine it with selection change event and you can determine if it is applied or not. 将其与选择更改事件结合起来,即可确定是否应用了它。

Basic Idea: 基本思路:

 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')); }) 
 div { outline: 1px solid black; } button.active { background-color: green; } 
 <div id="x" contenteditable="true"> Foo Bar </div> <button>Bold</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM