首页 > 解决方案 > execCommand 不适用于 div 作为事件侦听器

问题描述

我一直在谷歌上寻找,我似乎无法为这种情况找到一个可行的解决方案。我基本上是想用一个div调用触发器来成功执行document.execCommand(); 但我注意到 document.execCommand() 不适用于

div 作为事件侦听器,我知道这适用于按钮标签,但我不想使用带有此按钮的按钮,所以我怎样才能使用 div 来实现它,我知道你们中的一个人会说,你知道你不'不需要使用 document.execCommand 来做这样的事情

我知道这一点,但出于个人原因,我需要使用带有 document.execCommand 的 div 来执行此操作。

我的代码

document.querySelector('#trigger').addEventListener('click',underline);

function underline(){
  
  document.execCommand('underline', false, '');
  
}
#trigger{
  background-color: red;
  height: 50px;
  width: 100px;
  color: white;
  position: relative;
  border-radius: 8px;
  cursor: pointer;
  display: block;
}
<div id='trigger'></div><!--</trigger>-->

<p>Text highlight the word Adam and press the red trigger to add a underline to Adam.</p>

<p contenteditable='true'>Adam</p>

标签: javascript

解决方案


这段代码应该让它工作试试这个。

document.querySelector("#trigger").addEventListener('mousedown',function(event){event.preventDefault();});
document.querySelector('#trigger').addEventListener('click',underline);

function underline(){
  
  document.execCommand('underline', false, '');
  
}
#trigger{
  background-color: red;
  height: 50px;
  width: 100px;
  color: white;
  position: relative;
  border-radius: 8px;
  cursor: pointer;
  display: block;
}
<div id='trigger'></div><!--</trigger>-->

<p>Text highlight the word Adam and press the red trigger to add a underline to Adam.</p>

<p contenteditable='true'>Adam</p>

我从这篇文章中汲取了一些想法,并将此方法转换为适合您情况的事件侦听器版本。


推荐阅读