【出现原因】

页面中元素盒子的宽高都是通过rem进行设置的,而rem等于根元素html的font-size大小,而我们的font-size大小是通过js计算后进行设置的。

self-adaption.js:

function setFontSize() {
  document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + 'px';
};

window.addEventListener('resize', function () {
  setFontSize();
}, false);

setFontSize();

页面出现闪跳的原因是页面呈现的时候,js还没有执行,所以页面不正常。

 

【解决方案】

将js代码添加在head标签内,提前加载。

 

【补充说明】

在使用webpack或者vue...构建项目的时候,我们self-adaption.js文件通常是在页面的入口文件index.js中导入的。

index.js:

import './common/self-adaption.js'

但如果要在head中添加的话,就不能通过webpack进行打包,这时有两种做法:

(1)直接在script标签中添加js代码

<html>
<head>

<script>
function setFontSize() {
  document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + 'px';
};

window.addEventListener('resize', function () {
  setFontSize();
}, false);

setFontSize();
</script>

</head>
<body>

</body>
</html>

(2)使用script标签引入文件

<html>
<head>

<script src="./self-adaption.js"></script>

</head>
<body>

</body>
</html>

由于在html文件中引入的js文件不会经过webpack进行编译,所以文件不会被正确引用进来,同时self-adaption.js也不会被打包至dist文件夹中。

我们可以通过copy-webpack-plugin插件将self-adaption.js文件拷贝至dist输出文件夹中。

相关文章:

  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-27
  • 2021-11-25
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-04-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案