contenteditable and non button elements

前端 未结 4 1895
心在旅途
心在旅途 2021-02-09 23:32

I can easily do execcommand on a contenteditable selection if using a button. However using any other element fails.

http://jsbin.com/atike/edit

Why is this and

4条回答
  •  离开以前
    2021-02-10 00:10

    NicEdit uses a combination of methods.

    • Most toolbar elements have the "unselectable" attribute set - this works for Internet Explorer.

    • On the same elements, it registers for the "mousedown" event and overrides the default action - this prevents both text solution and focus. This is for browsers other than IE only.

    • Some toolbar elements need to be able to receive text focus and make selections, such as the field for inserting a link or image. For these, it saves the selection before the editor loses focus, then restores it after the user has finished editing and the changes need to be made.

      For how to implement it, check NicEdit's code. Search for the function names:

      • getSel
      • getRng
      • selRng
      • saveRng
      • restoreRng

      ...

      This uses the browser's getSelection() or document.selection to get the selection, getRangeAt() to convert it to a range, and addRange() or select() to restore that range to as a selection.

提交回复
热议问题