javascript - 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>
解决方案
这段代码应该让它工作试试这个。
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>
我从这篇文章中汲取了一些想法,并将此方法转换为适合您情况的事件侦听器版本。
推荐阅读
- android - Android:哪种方法最适合将 Json 放入 sqlite 数据库
- powershell - Powershell:如何从 OU 中的用户获取特定属性
- javascript - REACT.JS - 如何使用 react-openidconnect 调用登录
- swiftui - 如何在访问时增加已发布的 var
- amadeus - 来自艾玛迪斯的奇怪价格
- python - 嵌套列表上的负索引
- javascript - JavaScript:如何等待异步 api 调用完成
- database - MS Access/OleDB:没有为一个或多个必需参数提供值<-如何调试?
- javascript - babylon.js 如何访问其功能之外的网格
- python - Thompson Sampling:在 Python 中为人工智能添加正奖励到负奖励