繁体   English   中英

execCommand不适用于div作为事件监听器

[英]execCommand does not work with a div as a event listener

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

div作为事件侦听器,我知道它可以与button标记一起使用,但是我不想与此一起使用按钮,所以我如何使它与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> 

我把想法从这个职位和我转换这个方法为事件监听器版本,您的具体情况。

暂无
暂无

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

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