javascript - 为一个 Javascript 特征创建特征检测(intersectionObserver)

标签 javascript feature-detection intersection-observer

有没有一种方法可以在变量中存储一个内置的 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 returns true 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/

相关文章:

javascript - 将 jQuery 转换为原型(prototype) JS

javascript - 相对于视口(viewport),Intersection Observer 是否从跨域 iframe 内部工作?

javascript - 页面加载时立即触发 IntersectionObserver 回调

javascript - 对象不支持属性或方法 'autocomplete'

javascript - 在node-express应用程序中使用node-mysql建立共享连接

javascript - Angularjs:复选框和 ng-change

javascript - 如何检测浏览器是否支持聚焦于禁用元素?

image-processing - 如何识别同一对象的两个图像的变化

android - 使用 android 设备进行无标记检测的最适合检测图像的方法是什么?

javascript - 当表单元素离开视口(viewport)后,将键盘焦点从表单元素上移除