群里的朋友问了个问题:
chrome下面如何给flash加onclick事件?
搜索了下,找到了一些方法,但那些方法是说其他浏览器的,用一个button包住flash
在Chrome中 embed不支持onclick,但支持onmouseover,onmousedown,onmouseup
就利用这几个方法,自己拼凑一个click事件:
设置一个变量click
over的时候 +1
down的时候 +2
up 的时候 +4
out的时候 清零
发生up的时候,检查click变量,如果是7,那就是click事件了
<div style="border:1px #f00 solid; 486px">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="flash_obj" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="468" height="60">
<param name="movie" value="http://static.googleadsserving.cn/pagead/imgad?id=CICAgICQjvvjThDUAxg8MgiCYoyW5NzeKQ">
<param name="quality" value="high">
<param name="AllowScriptAccess" value="never">
<param name="wmode" value="opaque">
<param name="FlashVars" value="">
<embed src="http://static.googleadsserving.cn/pagead/imgad?id=CICAgICQjvvjThDUAxg8MgiCYoyW5NzeKQ" id="flash_embed" width="468" height="60" wmode="opaque" flashvars="" type="application/x-shockwave-flash" allowscriptaccess="never" pluginspage="http://www.macromedia.com/go/getflashplayer" >
</object>
</div>
<script>
if(!console){
console = { log: function(){} };
}
var timeoutID,
c = 0,
flashObj = document.getElementById('flash_obj'),
flashEmbed = document.getElementById('flash_embed');
function over(){
c |= 1;
console.log('mouse over', c);
}
function out(){
c = 0;
console.log('mouse out', c);
}
function down(){
c |= 2;
console.log('mouse down', c);
}
function up(){
c |= 4;
console.log('mouse up', c);
if(c === 7){
click();
c |= 8;
if(! timeoutID){
console.log('avoid twice click', c);
timeoutID = setTimeout(function(){
c ^= 8; //异或,a ^ b, ab不同则返回1
console.log('resume click', c);
timeoutID = undefined;
},100);
}
}
}
function click(){
console.log('trigger click', c);
alert('click');
}
if(flashObj){
flashObj.onmouseover = over;
flashObj.onmouseout = out;
flashObj.onmousedown = down;
flashObj.onmouseup = up;
}
if(flashEmbed){
flashEmbed.onmouseover = over;
flashEmbed.onmouseout = out;
flashEmbed.onmousedown = down;
flashEmbed.onmouseup = up;
}
</script>
呃,上面的四个事件都会同时发生两次,所以用了更高位(8)来避免重复事件,并在100毫秒后恢复