【发布时间】:2019-08-30 04:51:26
【问题描述】:
我有一些使用 ES6 模板字面量的 JS,我想确保它们可以回退到旧版浏览器。
通常要检测 javascript 功能,我会执行标准 if 语句来查看是否在窗口对象中检测到该功能:
if("JavascriptFeature" in window){
// do something with the feature
}
我将如何在下面的上下文中使用模板文字来做到这一点?
我有下面的代码,它基本上用于确保 100vh 属性在移动/iPad 上按需要工作,我想将 JS 包装成一个条件,只有在浏览器可以使用模板文字时才会触发:
JS
function resizeSection(){
// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
var vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);
}
resizeSection();
addEventListener("resize", resizeSection, false)
CSS
.heading-section {
/* Use vh as a fallback for browsers that do not support Custom Properties */
height: calc(100vh);
/*MODERN BROWSERS*/
height: calc(var(--vh, 1vh) * 100);
}
请注意:这不是 Detecting template literals in javascript 的重复,这是一个在非常不同的上下文中听起来相似的问题。
【问题讨论】:
-
如果浏览器 JavaScript 环境不理解模板文字语法,您的代码将根本没有机会运行,因为它会因语法错误而失败。
标签: javascript feature-detection template-literals