因爲瀏覽器安全機制問題,手機黑屏後,後臺運行瀏覽器停止運行計時器,
這裏使用的是H5的一個PageVisibility API(visibilitychange),熄屏時,開始計算黑屏時間,重啓時,再次計算;
另一個思路是也可使用iframe引入另一個頁面代碼使用全局變量進行計算時間,文本暫不深入;
廢話不多說,直接上代碼:
<input type="text" name="user-phone" class="user-phone" maxlength="11" οninput="value=value.replace(/^(0+)|[^\d]+/g,'')" >
<input type="button" class="aui-btn aui-btn-danger" id="subCode" οnclick="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);
}
}
});
}