因为浏览器安全机制问题,手机黑屏后,后台运行浏览器停止运行计时器,

这里使用的是H5的一个PageVisibility API(visibilitychange),熄屏时,开始计算黑屏时间,重启时,再次计算;

另一个思路是也可使用iframe引入另一个页面代码使用全局变量进行计算时间,文本暂不深入;

废话不多说,直接上代码:

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);

}

}

});

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐