【出現原因】
頁面中元素盒子的寬高都是通過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輸出文件夾中。