簡體   English   中英

將文本插入到由iframe外部的按鈕觸發的Designmode iframe中

[英]Inserting Text into a Designmode Iframe Triggered By a Button Outside the Iframe

我有一個可編輯的iframe,當用戶單擊iframe外部的按鈕時,我想在光標位置插入文本。 我正在嘗試使用以下代碼插入文本:

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);
};

我認為這失敗了,因為當我單擊按鈕時焦點發生了變化。 但是,我不確定如何糾正此問題。 謝謝您的幫助。

您對影響代碼插入的焦點轉移是正確的。

使用jQuery庫,您可以將焦點移回按鈕單擊綁定中的iframe:

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

在純JavaScript中,在執行insertAtCursor()之前先轉移焦點,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM