简体   繁体   English

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

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

I been looking all over on google and I cant seem to find a working solution for this situation. 我一直在Google各处搜寻,似乎无法找到这种情况的可行解决方案。 I basically want to use a div call trigger to successfully execute document.execCommand(); 我基本上想使用div调用触发器来成功执行document.execCommand(); but I notice that document.execCommand() don't work with a 但我注意到document.execCommand()不适用于

div as a event listener and I know this works with a button tag but I don't want to use a button with this so how can I get this working with a div and I know one of you guys will say, you know you don't need to use document.execCommand to do something like this div作为事件侦听器,我知道它可以与button标记一起使用,但是我不想与此一起使用按钮,所以我如何使它与div一起使用,我知道你们中的一个会说,你知道你没有不需要使用document.execCommand做这样的事情

and I am aware of that but for personal reasons I need to do this with a div with document.execCommand. 我知道这一点,但出于个人原因,我需要使用带有document.execCommand的div来执行此操作。

My code 我的密码

 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> 

This code should make it work try this out. 此代码应使其起作用,尝试一下。

 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> 

I took ideas from this post and I converted this method into a event listener version for your situation. 我把想法从这个职位和我转换这个方法为事件监听器版本,您的具体情况。

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

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