本文介绍一种JavaScript函数flashChecker(),用于区分PC与移动终端访问。针对移动端不支持Flash的问题,通过检测返回结果动态替换为.gif动画,PC端保持原样。代码包含ActiveXObject与navigator.plugins两种检测逻辑,并提供生成SwfHtml的辅助函数以处理点击跳转与透明层覆盖。
Flash兼容性与终端检测背景
鉴于众多移动终端设备无法支持Flash播放,导致网页中许多精美的Flash动画效果无法正常显示。若能准确识别访问Web页面的终端类型(是PC还是移动设备),便能针对性地采取解决方案。
当识别到访问终端为移动设备时,采用.gif格式图片替代Flash(.swf后缀)动画;而在PC端则保持原有设置不变。这种差异化处理策略能够实现较为理想的展示效果。
具体实现上,函数flashChecker()负责执行终端类型的检测工作。
终端检测函数实现
核心检测代码实现如下:
<script language="javascript" type="text/javascript">
/*
/* 用于检测当前访问是PC还是移动终端 */
/* 返回值说明:flashChecker().f == true 表示PC终端 */
/* 若为其他情况,则判定为移动终端 */
*/
function flashChecker() {
var hasFlash = 0;
var flashVersion = 0;
var isIE = /*@cc_on!@*/0;
if (isIE) {
var swf = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
if (swf) {
hasFlash = 1;
VSwf = swf.GetVariable("$version");
flashVersion = parseInt(VSwf.split(" ")[1].split(",")[0]);
}
}
} else {
if (navigator.plugins && navigator.plugins.length > 0) {
var swf = navigator.plugins["Shockwave Flash"];
if (swf) {
hasFlash = 1;
var words = swf.description.split(" ");
for (var i = 0; i < words.length; ++i) {
if (isNaN(parseInt(words[i]))) {
continue;
}
} flashVersion = parseInt(words[i]);
}
}
}
}
} } } } } return {
f: hasFlash, v: flashVersion
};
}
}; } 此外,还需要一个辅助函数来生成包含链接和Flash对象的HTML代码。
SwfHTML生成辅助函数
辅助函数代码如下:
<script language="javascript" type="text/javascript">
/*
/* 根据传入参数输出包含swf动画的HTML代码 */
/* url:点击swf动画后的跳转地址 */
/* swfLink:*.swf 素材文件的地址 */
*/
function GetSwfHtml(url, swfLink) {
html = "<a style='position: absolute; top: 0; left: 0; bottom: 0; right: 0; display: block; " +
"width: 100%; height: expression(this.parentNode.scrollHeight); filter: alpha(opacity=0);" +
"opacity: 0; background: #FFF;' href='" + url + "' target='_blank'>" +
"</a>" +
"<object width='590' height='55' align='middle'>" +
"<param name='allowScriptAccess' value='never' />" +
"<param name='quality' value='high' />" +
"<param name='wmode' value='transparent' />" +
"<param name='movie' value='" + swfLink+ "' />" +
"<embed wmode='transparent' src='" + swfLink+ "' quality='high' " +
"width='590' height='55' align='middle' allowscriptaccess='never' type='application/x-shockwave-flash' " +
"pluginspage='" + url + "' />" +
"</object>";
return html;
}
}