contenteditable and non button elements

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

    You could save the selection by using the mousedown event on the element being used instead of a button and restore it again after focussing the editable element in the click event.

    I've modified the example code: http://jsbin.com/atike/40/edit. Here's the code:

    function saveSelection() {
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                var ranges = [];
                for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                    ranges.push(sel.getRangeAt(i));
                }
                return ranges;
            }
        } else if (document.selection && document.selection.createRange) {
            return document.selection.createRange();
        }
        return null;
    }
    
    function restoreSelection(savedSel) {
        if (savedSel) {
            if (window.getSelection) {
                sel = window.getSelection();
                sel.removeAllRanges();
                for (var i = 0, len = savedSel.length; i < len; ++i) {
                    sel.addRange(savedSel[i]);
                }
            } else if (document.selection && savedSel.select) {
                savedSel.select();
            }
        }
    }
    
    $(function() {
      var savedSel;
    
      $('.bold').mousedown(function () {
        savedSel = saveSelection();
      });
    
      $('.bold').click(function () {
        $('#hello').focus();
        if (savedSel) {
          restoreSelection(savedSel);
        }
        document.execCommand("bold", false, null);    
      });
    });
    

提交回复
热议问题