0

JavaScriptファイルのライブラリ(主にCraftyjsライブラリ)によって制御および生成されたHTML5キャンバスがあります。
キャンバスは、互いの上に積み重ねられた 2 つの通常の html iframe (同じドメイン) を生成します。
キャンバスは、iframe から親への呼び出しに基づいて 2 つの iframe を切り替えます。そのため、共通の親からキャンバスを制御するコードに簡単にアクセスできることがわかります。

親キャンバスがiframeの関数を呼び出して、それらの特定の要素に焦点を当てるか、何らかの形でiframeに一般的に焦点を当てるようにしたい.
また、フォーカスを得るためにiframeを常にリロード/再作成する必要はありません。

 ---- In the Iframe ----
 //The head has a function "focusThis()" to focus on an element in the iframe
 //body also has onfocus="focusThis();"     

 //Call the parent to change to the other iframe
 parent.changeIframe();

 ---- In the parent's canvas JS code ----

 // I know the function and will hide/show the iframe, but it won't focus
 function changeIframe(){

     //For now, just switch randomly
     MODE = Math.floor(Math.random()*2);

    //I am hiding the iframes here, then showing the one that should be seen
    Crafty("Game1").each(function () {this.visible = false});
    Crafty("Game2").each(function () {this.visible = false});

    //Switch the iframes
    if(MODE){
         //Show this iframe
         Crafty("iframe1").each(function () {this.visible = true});

エラーがスローされない場合、Chrome またはFireFox
では何も実行されません。
(Object [object global] has no method 'focusThis') は一般的なエラーです

     //document.getElementById('iframe1').focus();
     //document.getElementById("iframe1").contentWindow.focusThis();
     //document.getElementById('iframe1').contentWindow.focusThis();

     //var iframe_window = window.frames["iframe1"];
     //iframe_window.focus();
     //iframe_window.contentDocument.body.focus();

     //window.parent.document.getElementById('iframe1').contentWindow.focusThis;
     //window.parent.document.getElementById('iframe1').contentWindow.focusThis();

     //window.frames["iframe1"].focus();
     //window.frames["iframe1"].contentWindow.focus();
     //window.frames["iframe1"].contentDocument.focus();

     var frame = document.getElementById("iframe1");
     if(frame){
          alert("yep");
              frame.contentWindow.focusThis();
         }
    }
     else{
          //....Same thing but for iframe2
    }
 }

どんな助けでも大歓迎です。

4

1 に答える 1

0

もう少しいじった後、私は問題を解決しました。
これにより、iframeをリロードしなくても問題が解決しました。

各 iframe の onload 関数にタイマーを設定します。このタイマーは、iframe にフォーカスがあるかどうかを iframe に伝える親フラグ変数 (MODE) と、それを伝える内部変数 (focused) に基づいて、要素自体にフォーカスしようとします。最終的に再び焦点が合ったら、焦点を合わせようとするのをやめます。

頭のどこか...

        var focused = false;
        function focusThis(){
            if(parent.MODE && !focused){
                document.getElementById("SOME_ELEMENT_I_WANT_FOCUSED").focus();
                focused = true;
            }
        }

onLoad のどこかに...

 var autoFocus = 
        setInterval(function(){if(parent.MODE && !focused) focusThis()},500);

本文の下のスクリプトのどこかに...

 parent.changeIframe();
 changeImage();
 if(!parent.MODE){
     //This element is just to have a place for focus to go when out of focus
     document.getElementById("NA").focus();
     focused = false;
 }
 else
     focused = true;
于 2013-04-28T18:19:51.383 に答える