24

私は、現在人気のあるすべてのブラウザー(IE9、Chrome、Firefox、Safari)で動作し、IE8までさかのぼって動作するものを本当に探しています。

フォーカスを失った後、Flash移動オブジェクトにフォーカスを設定する方法を探していましたが、これを行うための歴史的な方法はすべて失敗することがわかりました。それはまた別のセキュリティ問題だと思います。

そのため、document.activeElementのある種の変更イベントを監視する方法を探しています(ただし、「変更」は実際には発生しません)。

4

3 に答える 3

20

上記の@Jamesの答えは正しいですが。focusイベントの使用とともに、完全に機能するソリューションにするために、さらに詳細を追加しました。

<html>
<body>
    <input type="text" id="Text1" name ="Text1" value=""/>
    <input type="text" id="Text2" name ="Text2" value=""/>
    <SELECT><OPTION>ASDASD</OPTION><OPTION>A232</OPTION></SELECT>
    <INPUT TYPE="CHECKBOX" id="Check1"/>
    <INPUT type="TEXT" id="text3"/>
    <input type="radio"/>
    <div id="console"> </div>
    <textarea id="textarea1"> </textarea>
    <script>

        var lastActiveElement = document.activeElement;

        function detectBlur() {
            // Do logic related to blur using document.activeElement;
            // You can do change detection too using lastActiveElement as a history
        }

        function isSameActiveElement() {
            var currentActiveElement = document.activeElement;
            if(lastActiveElement != currentActiveElement) {
                lastActiveElement = currentActiveElement;
                return false;
            }

            return true;
        }

        function detectFocus() {
            // Add logic to detect focus and to see if it has changed or not from the lastActiveElement. 
        }

        function attachEvents() {
            window.addEventListener ? window.addEventListener('focus', detectFocus, true) : window.attachEvent('onfocusout', detectFocus);  

            window.addEventListener ? window.addEventListener('blur', detectBlur, true) : window.attachEvent('onblur', detectBlur);
        }

        attachEvents();

    </script>
</body>
</html>
于 2015-01-28T14:30:48.093 に答える
5

フォーカス/ブラーとフォーカスイン/フォーカスアウト(IE)イベントのキャプチャを組み合わせて使用​​できるようです。おそらくこのようなもの:

window.addEventListener ?
  window.addEventListener('blur', blurHappened, true)
  : window.attachEvent('onfocusout', blurHappened);

function blurHappened() {
  console.log('document.activeElement changed');
}

onfocusout泡立った「ぼやけ」をキャッチしますが、通常blurのオンaddEventListenerは「ぼやけ」をキャプチャします。

にチェックを追加する必要がある場合がありますblurHappened。テストしていないのでわかりません。

于 2012-04-05T20:41:53.417 に答える
1

私の経験では、クロスブラウザの問題に関する最良の情報源はQuirksmodeです。これが「明白な」(しかし使用できない)オプションへのリンクです-フォーカスとブラーイベント。

http://www.quirksmode.org/dom/events/blurfocus.html

奇妙なことに(そして驚くべきことに)、ここでの軟膏のフライはWebkitベースのブラウザーです。

もう1つのオプションは、インターバルタイマーを使用して、activeElementが唯一のオプションとして、またはフォーカス/ブラーのバックアップとして変更されたかどうかを確認することです。(キーの押下、マウスのクリック、およびタッチをリッスンして、activeElementが変更されるかどうかを確認することもできます。)これらのオプションをカバーする場合、intervalTimerをクリーンアップする必要はほとんどありません。

于 2012-04-05T20:37:08.723 に答える