gpt4 book ai didi

javascript - 如何使用 Google Closure Compiler 在 JavaScript 中检测 Internet Explorer?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:37:49 27 4
gpt4 key购买 nike

我有一个处理鼠标按钮事件的 JavaScript 函数。它必须能够区分鼠标左键和右键。遗憾的是,Internet Explorer 使用与所有其他浏览器不同的 event.button 值。我知道如何解释它们,但我需要知道该走哪条路。

我使用依赖于条件编译的 JavaScript hack 来做到这一点。是这样的:

if (/*@cc_on!@*/false) { IE fixup... }

我认为这是一种非常安全的方法,因为它基于无法伪造且不太可能被其他浏览器模仿的 JavaScript 解析器功能。

现在我正在使用 Google Closure Compiler 来打包我的 JavaScript 文件。我发现它也像删除任何其他注释一样删除了条件编译注释。所以我尝试了不同的技巧。其中之一是这样的:

if ("\v" == "v") { IE fixup... }

不幸的是,闭包编译器非常聪明,发现条件永远不会为真并删除了该代码。另外,我不喜欢它,因为 Microsoft 最终可能会修复那个\v 错误,然后检测失败。

我可以只读像 navigator.appName 之类的东西或它的名字,但这太容易伪造了。如果有人修改了他们的浏览器标识,他们就不太可能实现其他 event.button 行为......

Closure 编译器允许保留某些注释。我试过这个:

if (/**@preserve/*@cc_on!@*/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 (/*@cc_on!@*/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;
}

最佳答案

您的脚本开头有两行,似乎已经检测到浏览器是否为 IE。为什么不将其用作 if 语句的基础:

var IE = (!e.target && e.srcElement);
if (IE) {
!e.target && e.srcElement
}
// ...
if (IE) {
if (e.button & 1)
e.mouseButton = 0;
// ...

关于javascript - 如何使用 Google Closure Compiler 在 JavaScript 中检测 Internet Explorer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5127970/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com