2012-09-21 106 views
1

好吧,我有麻烦解决这个问题,我是一个PHP/C#Web开发人员,并且没有Javascript的经验或知识,我必须这样做有一点需要Javascript:Javascript倒数计时器,当窗口不在焦点时停止

当某个页面加载时,计数器启动。客户必须在此页面上停留20秒。之后,我想执行php代码。

所以有两个关于我的问题,第一:如果客户端离开页面(意思是页面没有对焦),我该如何停止计数器。

2)如何在JavaScript中执行php? ,或者从Javascript中调用一个php函数。

我到目前为止的代码是这样的:

<html> 
<head> 
</head> 

<body> 
<div id='timer'> 
<script type="text/javascript"> 

COUNTER_START = 20 

function tick() { 
    if (document.getElementById ('counter').firstChild.data > 0) { 
     document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1 
     setTimeout ('tick()', 1000) 
    } else { 
     document.getElementById ('counter').firstChild.data = 'done' 
    } 
} 

if (document.getElementById) onload = function() { 
    var t = document.createTextNode (COUNTER_START) 
    var p = document.createElement ('P') 
    p.appendChild (t) 
    p.setAttribute ('id', 'counter') 

    var body = document.getElementsByTagName ('BODY')[0] 
    var firstChild = body.getElementsByTagName ('*')[0] 

    body.insertBefore (p, firstChild) 
    tick() 
} 

</script> 
</div> 
</body> 
</html> 

,我也希望计时器开始滴答作响,当客户端回来

页面上

非常感谢乌拉圭回合的帮助提前

回答

4

你可以使用jQuery来做到这一点。
回收旧后#1,试试这个:

var window_focus; 
var counter = 1000; 

// on focus, set window_focus = true. 
$(window).focus(function() { 
    window_focus = true; 
}); 

// when the window loses focus, set window_focus to false 
$(window).focusout(function() { 
    window_focus = false; 
}); 

// this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/ 
$(document).one('click',function() { 
    // Run this function every second. Decrement counter if window_focus is true. 
    setInterval(function() { 
     $('body').append('Count: ' + counter + '<br>'); 
     if(window_focus) { counter = counter-1; } 
    }, 1000); 
}); 

演示老后
DEMO | Old So post

更新
大概是因为演示在4个iframe,那么$(窗口).focus位只适用于实际运行的代码(右下窗口)的iframe运行。

jQuery的
jQuery.com (How jQuery works) | Example (back to basics halfway down the page) | If you use the 2nd link, also read this

+0

这可能是太过分了,但在我开始在我的页面上的各个地方放置计时器代码之前,我会考虑编写一个定制的Javascript Timer对象,并在每个tick上接受回调并在到期时,并暴露像开始,停止和暂停方法...长期来说,可能会更简单的使用。只需0.02美元。 –

+0

确实 - 这似乎是一个明智的做法。 我不确定我想用javascript来检查是否有人在我的页面上花费了至少20秒。有些用户将完全禁用JavaScript。 –

+0

同意 - 这是可以得到真正的毛真快:)这种事情之一 –

1

在问候你对检测的第一个问题,如果窗口是失焦,看到这样的回答:Is there a way to detect if a browser window is not currently active?

这是可能的,但只有极新的浏览器都支持此所以它可能不会是有用的基于在目前的浏览器支持。

要从Javascript中触发PHP代码,您必须对服务器端PHP脚本进行AJAX调用才能调用PHP,因为JS是客户端,PHP是服务器端。