最近有個需求冯凹,運營希望將135編輯器里面的排版可以復(fù)制到我們自己的后臺谎亩,在app端實現(xiàn)排版樣式的多樣化。顯然宇姚,135編輯器復(fù)制過去的代碼的樣式是內(nèi)聯(lián)樣式匈庭,但我們的H5是將css文件統(tǒng)一處理,單位px
轉(zhuǎn)化為rem
,實現(xiàn)自適應(yīng)布局浑劳。由于內(nèi)聯(lián)樣式無法被轉(zhuǎn)化阱持,所以該需求簡化為就是將內(nèi)聯(lián)樣式的px
轉(zhuǎn)化為rem
。
參考微信的weixin/posthtml-px2rem的方式魔熏,稍微改寫一下
通過posthtml
處理html
,再利用posthtml-attrs-parser
插件提取style
屬性衷咽,最后利用正則表達(dá)式實現(xiàn)轉(zhuǎn)化
// pxToRem.js
'use strict';
var lodash = require('lodash');
var parseAttrs = require('posthtml-attrs-parser');
var posthtml = require('posthtml');
export default function (str, options) {
var pxRegex = /(\d*\.?\d+)px/ig;
options = lodash.extend({
rootValue: 16, // root font-size
unitPrecision: 5, // numbers after `.`
minPixelValue: 0 // set it 2 if you want to ignore value like 1px & -1px
}, options);
function createPxReplace(rootValue, unitPrecision, minPixelValue) {
return function (m, $1) {
// ignoring `PX` `Px`
if (m.indexOf('px') === -1) {
return m;
}
if (!$1) {
return m;
}
var pixels = parseFloat($1);
if (pixels < minPixelValue) {
return m;
}
return toFixed((pixels / rootValue), unitPrecision) + 'rem';
};
}
function toFixed(number, precision) {
var multiplier = Math.pow(10, precision + 1),
wholeNumber = Math.floor(number * multiplier);
return Math.round(wholeNumber / 10) * 10 / multiplier;
}
var pxReplace = createPxReplace(options.rootValue, options.unitPrecision, options.minPixelValue);
return Promise.try(() => {
return posthtml()
.use(function(tree) {
tree.match({attrs: {style: true}}, function (node) {
var attrs = parseAttrs(node.attrs);
for (var x in attrs['style']) {
if (attrs['style'].hasOwnProperty(x)) {
var styleValue = attrs['style'][x];
// e.g. style="width=10px; width=20px;"
if (typeof styleValue == 'object')
styleValue = styleValue[styleValue.length - 1];
var newStyleValue;
newStyleValue = styleValue.toString().replace(pxRegex, pxReplace);
attrs['style'][x] = newStyleValue;
}
}
node.attrs = attrs.compose();
return node;
});
})
.process(str)
.then(function(result) {
return result.html;
})
});
};
后端接口請求到的文章內(nèi)容是content: '<div><div>'
類似這樣的字符串,將其格式化
import pxToRem from 'px-to-rem.js';
pxToRem(str).then(res => { this.content = res; })