有没有一种方法可以在变量中存储一个内置的 javascript 方法,以便在某些浏览器中此方法不可用时设置不同的行为?
我的具体案例是 intersectionObserver,它在 Safari 或旧版 MS 浏览器中不可用。我有一些由此触发的动画,如果 intersectionObserver 不可用,我想将它们关闭。
本质上我想做的是:
var iO = intersectionObserver;
if ( !iO ) {
// set other defaults
}
我真的不想只为一个功能加载 polyfill 或库吗?
非常感谢
艾米丽
最佳答案
in Operator 广泛用于检测浏览器支持的功能。 JavaScript 功能作为 window
对象的属性在全局范围内可用。所以我们可以检查 window
元素是否有这个属性。
if("IntersectionObserver" in window){
/* work with IntersectionObserver */
}
if("FileReader" in window){
/* work with FileReader */
}
The
in
operator returnstrue
if the specified property is in the specified object or its prototype chain.
Syntax: prop in object
[source: developer.mozilla.org]
因此,您还可以将结果保存在 boolean
变量中,稍后在您的代码中使用它。
var iO = "IntersectionObserver" in window; /* true if supported */
if ( !iO ) {
// set other defaults
}
关于javascript - 为一个 Javascript 特征创建特征检测(intersectionObserver),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48793588/