0
可能重复:
JavaScript: How to find out when images are turned off in browser?如何检测图像在浏览器中是否被禁用?
什么是检测用户是否与图片浏览关闭,并添加另一个样式表头那么最简单的方法是什么?
是否有一个简短的JavaScript代码片段可以做到这一点,并支持浏览器?
可能重复:
JavaScript: How to find out when images are turned off in browser?如何检测图像在浏览器中是否被禁用?
什么是检测用户是否与图片浏览关闭,并添加另一个样式表头那么最简单的方法是什么?
是否有一个简短的JavaScript代码片段可以做到这一点,并支持浏览器?
这是我的解决方案:
<script type="text/javascript">
detectImageEnabledMode({
onDetectImageIsDisabled:function(){
alert('disabled');
},
onDetectImageIsEnabled:function(){
alert('enabled');
}
});
function detectImageEnabledMode(options){
/* define disabled/enabled actions */
var actionCounter = 0;
var enabledAction = (options.onDetectImageIsEnabled && typeof(options.onDetectImageIsEnabled)=='function')?options.onDetectImageIsEnabled:function(){};
var enaledActionRun = function(){
if(actionCounter) return;
actionCounter++;
enabledAction();
}
var disabledAction = (options.onDetectImageIsDisabled && typeof(options.onDetectImageIsDisabled)=='function')?options.onDetectImageIsDisabled:function(){};
var disabledActionRun = function(){
if(actionCounter) return;
actionCounter++;
disabledAction();
}
/* create image */
var img = new Image();
var currentTime = (new Date()).getTime();
if(navigator.appName.indexOf('Microsoft Internet Explorer') != -1){// ie
img.onload = enaledActionRun;
img.onabort = enaledActionRun;
img.onerror = enaledActionRun;
img.src = currentTime+'.'+currentTime+'?time='+currentTime;
setTimeout(function(){
disabledActionRun();
}, 0);
}else if (navigator.appName.indexOf('Opera') != -1) {// opera
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="+'?time='+(new Date()).getTime();
if(img.complete){
enaledActionRun();
}else{
disabledActionRun();
}
}else{// other
img.src = currentTime+'.'+currentTime+'?time='+currentTime;
if(img.complete){
disabledActionRun();
}else{
enaledActionRun();
}
}
}
// tested in: ff 2+, opera 9+, chrome, safari 4+, ie 6+
</script>
Live demo. 唯一的问题 - 即在最低异步:
setTimeout(function(){
disabledActionRun();
}, 0);
谢谢。旁边的问题:我应该更好地删除这篇文章吗? – Melros
重复的问题并不全是坏事。通过将“这个问题作为[链接]的重复而关闭”的方式,将一个问题的多个措词“指向”一个规范的答案可能是有用的。如有疑问,请[在meta上提出问题](http://meta.stackexchange.com/questions/ask),或者在您关注的问题上为主持人注意。 –