当浏览器窗口改变大小时,如何让文字也相应改变大小

js

 1 (function flexible (window, document) {
 2   var docEl = document.documentElement
 3   var dpr = window.devicePixelRatio || 1
 4 
 5   // adjust body font size
 6   function setBodyFontSize () {
 7     if (document.body) {
 8       document.body.style.fontSize = (12 * dpr) + 'px'
 9     }
10     else {
11       document.addEventListener('DOMContentLoaded', setBodyFontSize)
12     }
13   }
14   setBodyFontSize();
15 
16   // set 1rem = viewWidth / 10
17   function setRemUnit () {
18     var rem = docEl.clientWidth / 24
19     console.log(docEl.clientHeight)
20     console.log(window)
21     docEl.style.fontSize = rem + 'px'
22   }
23 
24   setRemUnit()
25 
26   // reset rem unit on page resize
27   window.addEventListener('resize', setRemUnit)
28   window.addEventListener('pageshow', function (e) {
29     if (e.persisted) {
30       setRemUnit()
31     }
32   })
33 
34   // detect 0.5px supports
35   if (dpr >= 2) {
36     var fakeBody = document.createElement('body')
37     var testElement = document.createElement('div')
38     testElement.style.border = '.5px solid transparent'
39     fakeBody.appendChild(testElement)
40     docEl.appendChild(fakeBody)
41     if (testElement.offsetHeight === 1) {
42       docEl.classList.add('hairlines')
43     }
44     docEl.removeChild(fakeBody)
45   }
46 }(window, document))

在css上将px定值换算为rem,这里的话如果电脑宽度1920,则1920/24,换算比例是80px=1rem

posted @ 2020-11-10 16:47  俩只猫  阅读(324)  评论(0编辑  收藏  举报