return focus to contenteditable after execCommand?

前端 未结 5 1774
臣服心动
臣服心动 2021-02-04 08:56

I have the following code demonstrating contenteditable property and a button that will inject bold text into the paragraph with contenteditable area. My question is how to retu

相关标签:
5条回答
  • 2021-02-04 09:17

    You may want to store the last clicked item in a variable and then call .focus() on it after the .execCommand has been executed. Something like this, I guess:

     $(function(){
            $('p.editable').click(function() {
                var clickedItem = $(this);
                clickedItem.attr('contenteditable', true).focus();
                $('#bold').click(function (){
                        document.execCommand('bold', false, true);
                        clickedItem.focus();
                });
            });
        });
    

    This way you can also remove the "contenteditable" attribute from the markup...

    HTH

    0 讨论(0)
  • 2021-02-04 09:26

    You can just use the jQuery .focus() function to focus it. This should work:

    var current;
    $(function(){
        $("p[contenteditable]").focus(function() {
            current = this;
        });
    
        $('#bold').click(function (){
                document.execCommand('bold', false, true);
                $(current).focus();
        });
    });
    

    This just keeps track of the currently editing field every time it is focused by the user, and when the bold button is clicked focus is set back to that field.

    0 讨论(0)
  • 2021-02-04 09:33

    HTML:

    <button onclick="doRichEditCommand('bold')" style="font-weight:bold;">B</button>
    

    JavaScript:

    function doRichEditCommand(aName, aArg){
        getIFrameDocument('editorWindow').execCommand(aName,false, aArg);
        document.getElementById('editorWindow').contentWindow.focus()
    }
    

    Refer this may help you:

    https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla

    0 讨论(0)
  • 2021-02-04 09:33

    If you're in an iframe, call focus() on the default view.

    myiframedocument.execCommand('Bold',false,null);
    myiframedocument.defaultView.focus();
    
    0 讨论(0)
  • 2021-02-04 09:35

    YOU SHOULD USE .contents()

    var current;
    $(function(){
        $("p[contenteditable]").focus(function() {
            current = this;
        });
    
        $('#bold').click(function (){
                document.execCommand('bold', false, true);
                $(current).contents().focus();
        });
    });
    
    0 讨论(0)
提交回复
热议问题