Keep selection made on editable DIV when focus is on other element

感情迁移 提交于 2019-12-12 19:20:00

问题


I have had this problem for a long time and I just can't figure out how to fix it. I want to create a simple WYSYWYG editor and I have some problems.

Currently I have this:

<div id="editor" contenteditable="true"></div>
<input type="button" value="B" 
       onmousedown="document.execCommand('bold',false,null); return false;"/>

So, if I have some text inside my DIV, select it and click on "B" it is converted to BOLD, and remains selected, but this doesn't work on Opera and IE.

I just don't know how to make the editable DIV not only keep the focus but also the text selection.

Any idea?


回答1:


Two possible options are:

  • Use mousedown instead of click and prevent the default browser action: http://jsfiddle.net/dA9NK/
  • Make the button unselectable: http://jsfiddle.net/8hpvv/


来源:https://stackoverflow.com/questions/12519938/keep-selection-made-on-editable-div-when-focus-is-on-other-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!