【问题标题】:$(window).focus() not executed properly in Chrome$(window).focus() 在 Chrome 中未正确执行
【发布时间】:2016-07-18 13:25:39
【问题描述】:

我想跟踪我网页上 AdSense 元素的点击次数。为了实现这一点,我将焦点放在窗口对象上,如果它失去焦点,我会检查鼠标是否在 AdSense iFrame 的区域中。然后我又把焦点放回窗口。

这行得通。但在 Chrome 中它只工作一次。因此,如果我单击一个 adSense 广告(在新标签中打开),然后单击另一个广告,则该事件不再触发。

如果我在控制台中执行 $(window).focus(),onBlur 事件会再次触发 - 但在我的代码中执行的 $(window).focus() 不会显示任何效果。我也尝试了超时,但没有成功。

有什么想法吗?

trackElements("#contentAdSense, #fallbackAdSense, #sidebarAdSense");

function trackElements (elementsToTrack) 
{
  var isOverElement = false;

  $(window).focus();

  $(elementsToTrack).mouseenter(function(e){
      isOverElement = e.currentTarget.id;
  });

  $(elementsToTrack).mouseleave(function(e){
       isOverElement = false;
  });

  $(window).blur(function(e){
      windowLostBlur();
  });

  function windowLostBlur () 
  {
      if (isOverElement) 
      {
          console.log(isOverElement);
          $(window).focus();
      }
  };

};

简化版:https://jsfiddle.net/327skdns/2/

【问题讨论】:

  • 能否请您创建一个小提琴,以便我们可以在 chrome 中检查?
  • 这里是简化版-> jsfiddle.net/327skdns/2

标签: javascript jquery events focus onblur


【解决方案1】:

这是一个记录在案的 Chrome 错误:jQuery focus not working in Chrome

您需要使用 setTimeout 包装您的 focus() 调用:

trackElements("#contentAdSense, #fallbackAdSense, #sidebarAdSense");

function trackElements (elementsToTrack) 
{
    var isOverElement = false;

    $(window).focus();

    $(elementsToTrack).mouseenter(function(e){
      isOverElement = e.currentTarget.id;
    });

    $(elementsToTrack).mouseleave(function(e){
       isOverElement = false;
    });

    $(window).blur(function(e){
      windowLostBlur();
    });

    function windowLostBlur () 
    {
      if (isOverElement) 
      {
          console.log(isOverElement);
          setTimeout( function(){ $(window).focus(); }, 50 );
      }
    };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多