因为浏览器安全机制问题,手机黑屏后,后台运行浏览器停止运行计时器,
这里使用的是H5的一个PageVisibility API(visibilitychange),熄屏时,开始计算黑屏时间,重启时,再次计算;
另一个思路是也可使用iframe引入另一个页面代码使用全局变量进行计算时间,文本暂不深入;
废话不多说,直接上代码:
<input type="text" name="user-phone" class="user-phone" maxlength="11" oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" >
<input type="button" class="aui-btn aui-btn-danger" id="subCode" onclick="getCode(this)" value="获取验证码" >
var timer=null;
function getCode(t){
var time=29;
var that= $(t);
timer=setInterval(function(){
if(time<=0){
that.val("");
that.val("重新发送");
that.attr("disabled",false);
that.removeClass('code_style');
clearInterval(timer);
that.attr("time",0);
}else {
that.attr("disabled",true);
that.val("");
that.val("剩余"+(time)+"秒");
that.attr("time",time);
time--;
that.addClass('code_style');
}
},1000);
var cede_times = 0;
var b=0;
document.addEventListener("visibilitychange",function()
{
if(document.visibilityState=="hidden") {
b=new Date().getTime();
cede_times=$("#subCode").attr("time");
}else {
var betweenMs = parseInt(new Date().getTime()) - parseInt(b);
var betweens = Math.round(betweenMs / 1000);
var booleans=parseInt(cede_times)-betweens;
if(booleans>0){
that.attr("time",booleans);
time=booleans;
that.val("剩余"+(time)+"秒");
}else{
that.val("");
that.val("重新发送");
that.attr("disabled",false);
that.removeClass('code_style');
clearInterval(timer);
that.attr("time",0);
}
}
});
}