我有一个处理鼠标按钮事件的JavaScript函数。它必须能够区分鼠标左键和右键。可悲的是,Internet Explorer对event.button使用的值不同于其他所有浏览器。我知道如何解释它们,但我需要知道要走哪条路。如何使用Google Closure Compiler在JavaScript中检测Internet Explorer?
我做了一个JavaScript的黑客工具,依赖于条件编译。它是这样的:
if (/*@[email protected]*/false) { IE fixup... }
我认为这是一个相当安全的方法,因为它是基于无法伪造并不太可能被其他浏览器模仿的JavaScript分析器功能。
现在我使用的是谷歌关闭编译收拾我的JavaScript文件。我发现它也像其他评论一样删除了条件编译注释。所以我尝试了不同的黑客。其中之一是这样的:
if ("\v" == "v") { IE fixup... }
不幸的是,闭包编译器很聪明,发现条件永远不会是真的,并删除该代码。另外,我不喜欢它,因为微软可能最终修复这个\ v bug,然后检测失败。
我可以读的东西像navigator.appName或者它叫什么,但是这是太容易伪造。如果有人修改了自己的浏览器识别,他们是不太可能实现的其他event.button行为......
Closure编译器允许保留一定意见。我尝试这样做:
if (/**@preserve/*@[email protected]*/false) { IE fixup... }
虽然这种压缩后生成所需的结果,它不是在其源形式的功能条件注释。但出于调试的原因,我需要我的JavaScript文件同时工作压缩和未压缩。
究竟有没有前途,我得到这个工作,而无需手动修改压缩JS文件?
对于参考,这是我原来的形式完整的功能:
function findEvent(e)
{
e = e || event; // IE
if (!e.target && e.srcElement) // IE
e.target = e.srcElement;
if (isSet(e.button))
{
// Every browser uses different values for the mouse buttons. Correct them here.
// DOM says: 0 = left, 1 = middle, 2 = right (multiple buttons not supported)
// Opera 7 and older and Konqueror are not specifically handled here.
// See http://de.selfhtml.org/javascript/objekte/event.htm#button
if (/*@[email protected]*/false) // IE - http://dean.edwards.name/weblog/2007/03/sniff/ - comment removed by Google Closure Compiler
{
if (e.button & 1)
e.mouseButton = 0;
else if (e.button & 2)
e.mouseButton = 2;
else if (e.button & 4)
e.mouseButton = 1;
}
else
e.mouseButton = e.button;
}
return e;
}
是event.srcElement存在一个肯定的条件来检测IE?我完全没有这方面的细节。 srcElement/target代码适用于单行(检测功能,而不是浏览器),但可能会在其他任何地方失败。不幸的是,event.button的值不能被特征检测解释。 – ygoe 2011-02-28 07:11:21