简体   繁体   中英

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. I basically want to use a div call trigger to successfully execute document.execCommand(); but I notice that document.execCommand() don't work with a

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

and I am aware of that but for personal reasons I need to do this with a div with document.execCommand.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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