我的 JavaScript 中有一个反引号,以使我的网站在移动 Chrome 上正确呈现。问题是反引号虽然在 IE 中不需要,但会导致 IE 的 javascript 中的所有内容出错并停止工作。
我尝试简单地将其替换为双引号,但这不起作用。我还考虑过制作一个单独的 javascript 页面,该页面只能在 IE 或桌面上运行,但这似乎不太理想。最好可以更改该代码行,使其具有相同的效果并在所有浏览器中工作。
有问题的代码行是:
document.documentElement.style.setProperty('--vh', `${vh}px`);
// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
let 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`);
body {
background-color: #333;
}
.module {
height: 100vh; /* Use vh as a fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
margin: 0 auto;
max-width: 30%;
}
.module__item {
align-items: center;
display: flex;
height: 20%;
justify-content: center;
}
.module__item:nth-child(odd) {
background-color: #fff;
color: #F73859;
}
.module__item:nth-child(even) {
background-color: #F73859;
color: #F1D08A;
}
<div class="module">
<div class="module__item">20%</div>
<div class="module__item">40%</div>
<div class="module__item">60%</div>
<div class="module__item">80%</div>
<div class="module__item">100%</div>
</div>
该脚本来自此处:https://css-tricks.com/the-trick-to-viewport-units-on-mobile/
这是一种设置 vh 的方法,使其在 Chrome 和 Firefox 中更加静态。
最佳答案
模板文字语法是 ES6 的一项功能,let
关键字也是如此。 ES5 的方法是使用 var
和普通字符串连接:
// 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');
但是当您有大量代码时,这可能会变得非常乏味,并且使阅读代码变得更加困难。更好的通用解决方案是通过 Babel 运行代码。首先,它会自动将 ES6+ 语法转换为 ES5 语法。 (请注意,Babel 默认情况下仅转译语法 - ES6+ 对象和方法,例如 Array.prototype.includes
,将在古老的浏览器中工作,例如仅当您也使用 polyfill 时才使用 IE)
关于javascript - Internet Explorer 中反引号的替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54057491/