rem.js 1.1 KB

1234567891011121314151617181920212223242526272829
  1. // ---------------------第四种----------------------- 18fontsize = (18/100)rem
  2. (function (doc, win) {
  3. const docEl = doc.documentElement
  4. const head = docEl.getElementsByTagName('head')[0]
  5. const resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
  6. const metaEl = doc.createElement('meta')
  7. metaEl.name = 'viewport'
  8. metaEl.content = 'initial-scale=1,maximum-scale=1, minimum-scale=1'
  9. head.appendChild(metaEl)
  10. const recalc = function () {
  11. // 增加判断PC/and/ios
  12. const isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  13. const isAndroid = navigator.userAgent.includes('Android') || navigator.userAgent.includes('Linux') // g
  14. // 1rem =100px
  15. let width = docEl.clientWidth
  16. if (isAndroid || isIOS) {
  17. docEl.style.fontSize = parseInt((100 * (width / 750)) * 2) + 'px'
  18. } else {
  19. if (width < 1920) {
  20. width = 1920
  21. }
  22. docEl.style.fontSize = (100 * (width / 1920)) + 'px'
  23. }
  24. }
  25. recalc()
  26. if (!doc.addEventListener) { return }
  27. win.addEventListener(resizeEvt, recalc, false)
  28. console.log('已自适应')
  29. })(document, window)