简体   繁体   English

将文本插入到由iframe外部的按钮触发的Designmode iframe中

[英]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. 我有一个可编辑的iframe,当用户单击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: 使用jQuery库,您可以将焦点移回按钮单击绑定中的iframe:

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

In pure javascript, shift focus before executing insertAtCursor() like so: 在纯JavaScript中,在执行insertAtCursor()之前先转移焦点,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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