窗口模糊事件

时间:2018-05-09 11:15:17

标签: javascript jquery

我试图阻止用户打开标签/窗口。我使用以下代码:

 window.onblur = function() {
   alert(
     'Please do not switch the test window. You may be disqualified from the test'
   );
 };

它适用于窗口切换但是当我尝试打开/切换标签时,它会无限循环地重复显示警告框。

我知道原因。这是因为警报框本身会触发模糊事件,导致无限次调用。我不想使用console.log,因为我想向用户传达警告。

2 个答案:

答案 0 :(得分:0)

我认为这是因为窗口在显示警报时会失去焦点,因此我认为这样的事情应该有用(代码未经过测试):

var isBlurred = false;

window.onblur = function() {
    if (!isBlurred) {
        isBlurred = true;
        alert('Please do not switch the test window. You may be disqualified from the test');
    }
};

window.onfocus = function() {
    isBlurred = false;
};

答案 1 :(得分:0)

您可以使用标记来检查通知是否已开启,并在重置该标志时使用较小的延迟。



var noticeIsOn = false;

window.addEventListener('blur', function() {
  if (!noticeIsOn) {
    noticeIsOn = true;
    
    alert('Please do not switch the test window. You may be disqualified from the test');
    
    setTimeout(function() {
      noticeIsOn = false;
    }, 100)
  }
});