2016-07-18 78 views
1

正确执行我想跟踪我的网页上针对AdSense元素的点击次数。为了实现这个目标,我把焦点的窗口对象,如果它失去焦点,我检查如果鼠标是在AdSense的iFrame的区域。然后我再把焦点放回窗口。

这工作。但是在Chrome中它只能运行一次。所以,如果我点击AdSense广告(在新标签中打开),然后我点击一个又一个,该事件不会再触发。

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

任何想法?

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/

+1

可以请你创建一个小提琴,让我们可以检查铬? – Drone

+0

这里是一个简化版本 - > https://jsfiddle.net/327skdns/2/ – hwechselberg

回答

0

这是一个文档浏览器BUG: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); 
     } 
    }; 
}