(function (win, lib) { var doc = win.document var docEl = doc.documentElement var metaEl = doc.querySelector('meta[name="viewport"]') var flexibleEl = doc.querySelector('meta[name="flexible"]') var dpr = 0 var scale = 0 var tid var flexible = lib.flexible || (lib.flexible = {})
if (metaEl) { console.warn('将根据已有的meta标签来设置缩放比例') var match = metaEl .getAttribute('content') // eslint-disable-next-line no-useless-escape .match(/initial\-scale=([\d\.]+)/) if (match) { scale = parseFloat(match[1]) dpr = parseInt(1 / scale) } } elseif (flexibleEl) { var content = flexibleEl.getAttribute('content') if (content) { // eslint-disable-next-line no-useless-escape var initialDpr = content.match(/initial\-dpr=([\d\.]+)/) // eslint-disable-next-line no-useless-escape var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/) if (initialDpr) { dpr = parseFloat(initialDpr[1]) scale = parseFloat((1 / dpr).toFixed(2)) } if (maximumDpr) { dpr = parseFloat(maximumDpr[1]) scale = parseFloat((1 / dpr).toFixed(2)) } } }
flexible.dpr = win.dpr = dpr flexible.refreshRem = refreshRem flexible.rem2px = function (d) { var val = parseFloat(d) * this.rem if (typeof d === 'string' && d.match(/rem$/)) { val += 'px' } return val } flexible.px2rem = function (d) { var val = parseFloat(d) / this.rem if (typeof d === 'string' && d.match(/px$/)) { val += 'rem' } return val } })(window, window['lib'] || (window['lib'] = {}))
引入
在 main.js 中引入 flexible:
1 2 3
import'lib-flexible' // or import'./assets/js/flexible.js'