简体   繁体   中英

Inserting Text into a Designmode Iframe Triggered By a Button Outside the Iframe

I have an editable iframe and I would like to insert text at the cursor location when the user clicks a button that is outside the iframe. I am trying to use the following code to insert the text:

function insertAtCursor(iframename, text, replaceContents) {
      if(replaceContents==null){replaceContents=false;}
      if(!replaceContents){//collapse selection:
         var sel=document.getElementById(iframename).contentWindow.getSelection()
         sel.collapseToStart()
      }
      document.getElementById(iframename).contentWindow.document.execCommand('insertHTML', false,     text);
};

I think that this is failing because the focus changes when I go to click the button. However, I am not sure how to correct this. Thank you for your help.

You're correct about the focus shift affecting your code insert.

Using the jQuery library, you can shift focus back to the iframe in the button's click binding:

$('#button').click(function(event) {
    event.preventDefault();
    $('#iframe').focus();
    insertAtCursor('iframe', 'test-text', null);
});

In pure javascript, shift focus before executing insertAtCursor() like so:

document.getElementById('iframe').focus()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM