關於手機適配的方案(transform)
阿新 • • 發佈:2017-10-24
document ready 方法 排版 class fontsize height nth script
手機按照750px 的設計稿樣式排版。頁面在750px的屏幕上顯示正常
1 var doc = document 2 var docEle = doc.documentElement 3 var width 4 function setRootFontSize(){ 5 width = docEle.getBoundingClientRect().width 6 doc.querySelector(‘#main‘).style = `transform: scale(${width / 750})`7 } 8 setRootFontSize()
在其他尺寸的屏幕上,按照比例進行縮放。
遇到的問題: 由於在樣式加載後進行了縮放,所以body的高度沒有改變,仍然是縮放之前的高度,所以在頁面加載之後需要設置重新設置body的高度,方法如下:
1 function setHeight() { 2 console.log(doc.querySelector(‘#main‘).clientHeight) 3 doc.body.style.height = (doc.querySelector(‘#main‘).clientHeight * width / 750) + ‘px‘ 4} 5 if (doc.readyState === "complete") { 6 setHeight() 7 } else { 8 window.onload = setHeight 9 }
document.readystatus 在加載中是loading狀態,加載完成之後轉為complate狀態。需要在此時重新設置body的高度、
完整代碼:
<script type="text/javascript"> void function (){var doc = document var docEle = doc.documentElement var width function setRootFontSize(){ width = docEle.getBoundingClientRect().width doc.querySelector(‘#main‘).style = `transform: scale(${width / 750})` } setRootFontSize() function setHeight() { console.log(doc.querySelector(‘#main‘).clientHeight) doc.body.style.height = (doc.querySelector(‘#main‘).clientHeight * width / 750) + ‘px‘ } if (doc.readyState === "complete") { setHeight() } else { window.onload = setHeight } }() </script>
關於手機適配的方案(transform)