本文实现了用javascript检测手机网络是否中断,实现某些页面提醒或功能禁用,从而优化用户体验。
有代码有真相,代码如下:/*检测网络状况*/
var testnet_on=function(){
var img=new Image();
img.id="testnet";
img.οnlοad=function(){
$("#testnet").remove();
if(net_on==0 && $("#playbtn").is(":not(.stopped)")){
playmusic(currentinfo.id);
}
net_on=1;
};
img.οnerrοr=function(){
$("#testnet").remove();
net_on=0;
};
img.src="http://www.baidu.com/img/baidu_jgylogo3.gif?t="+(new Date().getTime());
img.style.display="none";
document.body.appendChild(img);
}
var net_on=1;
test_interval=setInterval(testnet_on,10000);
/*检测网络状况*/
通过不断请求1个像素的图片,如果图片请求失败,触发img.onerror事件,事件回调中修改全局变量testnet_on=0,说明断网了,否则触发onload事件,testnet_on=1.
当然图片不能太大,不然浪费用户流量,会导致用户反感就得不偿失来了。
本文由php中文网提供,
文章地址:http://www.php.cn/js-tutorial-374005.html
请勿转载~~~