X

JavaScript — определить, что фокус на странице

Как определить, что фокус находится в браузере или что пользователь в данный момент просматривает именно нужную страницу, а не она открыта в скрытой закладке?

Очень просто:

<script type="text/javascript">
function onBlur() {
    //$("#div").html('Фокуса на странице нет');
	document.getElementById('div').innerHTML = 'Фокуса на странице нет';
    //$('body').css('background', 'lightgrey');
	document.body.style.background = "lightgrey";
};
function onFocus(){
    //$("#div").html('Фокус на странице');
	document.getElementById('div').innerHTML = 'Фокуса на странице';
    //$('body').css('background', 'white');
	document.body.style.background = "white";
};
if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}
</script>


Пример работы:
http://razrabot.com/examples/page-focus.html

admin:

View Comments (4)

  • Pavel,
    конструкция /*@cc_on .... */ - включает условные комментарии (conditional compilation) в IE браузерах, для других браузеров это работает как обычный многострочный комментарий.

    Поэтому для IE данная конструкция сработает, как !false, т.е. true

  • Надо бы добавить в название - Javascript (JQuery) - определить....
    Я честно говоря, думал что тут будет чистый JS.

    Notice: Trying to get property of non-object in /home/content/24/5376624/html/itifru/wp-content/plugins/wp-lightbox-2/wp-lightbox-2.php on line 155

    Warning: Cannot modify header information - headers already sent by (output started at /home/content/24/5376624/html/itifru/wp-content/plugins/wp-lightbox-2/wp-lightbox-2.php:155) in /home/content/24/5376624/html/itifru/wp-includes/comment.php on line 517

    Warning: Cannot modify header information - headers already sent by (output started at /home/content/24/5376624/html/itifru/wp-content/plugins/wp-lightbox-2/wp-lightbox-2.php:155) in /home/content/24/5376624/html/itifru/wp-includes/comment.php on line 518

    Warning: Cannot modify header information - headers already sent by (output started at /home/content/24/5376624/html/itifru/wp-content/plugins/wp-lightbox-2/wp-lightbox-2.php:155) in /home/content/24/5376624/html/itifru/wp-includes/comment.php on line 519

    Warning: Cannot modify header information - headers already sent by (output started at /home/content/24/5376624/html/itifru/wp-content/plugins/wp-lightbox-2/wp-lightbox-2.php:155) in /home/content/24/5376624/html/itifru/wp-includes/pluggable.php on line 1171

    Вот так ваш сайт отвечает мне на отправку коммента)

    • OJler, jQuery тут используется только для показывание работы скрипта. Переписал эту часть использую только js.

      Сообщения исправил. Спасибо

Related Post