【问题标题】:Create Feature detection for One Javascript Feature (intersectionObserver)为一个 Javascript 功能创建功能检测 (intersectionObserver)
【发布时间】:2018-07-25 09:41:47
【问题描述】:

有没有办法将内置的 javascript 方法存储在变量中,以便在该方法在某些浏览器中不可用时设置不同的行为?

我的具体情况是针对 Safari 或旧版 MS 浏览器中不可用的 intersectionObserver。我有一些由此触发的动画,如果intersectionObserver 不可用,我想关闭它们。

基本上我想做的是:

var iO = intersectionObserver;

if ( !iO ) {
 // set other defaults
}

我真的不想为一个功能加载 polyfill 或库?

非常感谢

艾米丽

【问题讨论】:

  • if("IntersectionObserver" in window)? var iO = window.IntersectionObserver;?
  • 这不起作用 - 它还会在我的代码编辑器@Xufox 中引发错误?
  • 什么作用?哪个错误?
  • 那行代码。我尝试使用它来创建变量,但它在我的编辑器中强调它是一个错误并且不会处理代码?此外,我以前从未见过结合两个问号的 if 语句。我应该包括问号吗?除非那是我想知道的东西的简写?我真的很困惑。
  • 我没有将问号标记为代码,所以它们不属于代码。

标签: javascript feature-detection intersection-observer


【解决方案1】:

in Operator 广泛用于检测浏览器支持的功能。 JavaScript 功能可作为window 对象的属性在全球范围内使用。所以我们可以检查window元素是否有这个属性。

if("IntersectionObserver" in window){
    /* work with IntersectionObserver */
}
if("FileReader" in window){
    /* work with FileReader */
}

如果指定的属性在 指定的对象或其原​​型链。
语法:对象中的道具
[来源:developer.mozilla.org]

因此,您还可以将结果保存在 boolean 变量中,稍后在您的代码中使用。

var iO = "IntersectionObserver" in window; /* true if supported */

if ( !iO ) {
 // set other defaults
}

【讨论】:

  • 谢谢穆尼姆。我不敢相信有人否决了这个问题。如果您愿意,请随时为它投票。
  • 这也是official w3c polyfill 检测它的方式
猜你喜欢
  • 2012-11-17
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
相关资源
最近更新 更多