[原简书]将内联样式的px转化为rem
将之前写在简书的⽂章搬过来,荒废了⼀段时间,抓紧时间充电
最近有个需求,运营希望将135编辑器⾥⾯的排版可以复制到我们⾃⼰的后台,在app端实现排版样式的多样化。显然,135编辑器复制过去的代码的样式是内联样式,但我们的H5是将css⽂件统⼀处理,单位px转化为rem,实现⾃适应布局。由于内联样式⽆法被转化,所以该需求简化为就是将内联样式的px转化为rem。
参考的的⽅式,稍微改写⼀下
通过posthtml处理html,再利⽤posthtml-attrs-parser插件提取style属性,最后利⽤正则表达式实现转化
// 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 = d({
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);
und(wholeNumber / 10) * 10 / multiplier;
}
var pxReplace = Value, options.unitPrecision, options.minPixelValue);
(() => {
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.
// e.g.
if (typeof styleValue == 'object')
styleValue = styleValue[styleValue.length - 1];
var newStyleValue;
newStyleValue = String().replace(pxRegex, pxReplace);
attrs['style'][x] = newStyleValue;
}
}
node.attrs = attrspose();
return node;
});
})
.process(str)
.then(function(result) {
return result.html;
})
});
135编辑器手机版};
后端接⼝请求到的⽂章内容是content: '<div><div>'类似这样的字符串,将其格式化import pxToRem from 'px-to-rem.js';
pxToRem(str).then(res => { t = res; })

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。