contenteditable and non button elements

前端 未结 4 1892
心在旅途
心在旅途 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:00

    What is happening is that when you click a text node, the browser wants to select that text. Buttons are not a part of the text flow and will therefore not trigger a new selection.

    All you have to do is prevent the browser from performing a re-selection. When the click event you are currently observing runs the selection has already occurred and it's too late to act. The action starts to take place on mousedown for all browsers expect MSIE, which has a special selection events.

    This works for me across browsers:

    jQuery('.bold')
      .attr('unselectable','on') // prevents selection in MSIE
      .bind('mousedown',function (e) {
        document.execCommand("bold", false, null);
        e.preventDefault(); // prevents selection in all but MSIE
      });
    

    There are a few complications with using MSIE's selection events (such as having to block dragging as well), so it's easier just to knock out the selectability of the element you are using as a button with the specialized attribute unselectable (needs the value "on").

    You can obviously still perform the execCommand handling in click events and just run the selection prevention code on all elements intended as "buttons":

    jQuery('.buttonlike')
      .attr('unselectable','on') // prevents selection in MSIE
      .bind('mousedown',function (e) {
        e.preventDefault(); // prevents selection in all but MSIE
      });
    
    jQuery('#edit-bold').click(function(){
      document.execCommand("bold", false, null);
    });
    

提交回复
热议问题