JS查找并计算和替换富文本中的px为响应式单位

因为在做官网响应式时有部分后台返回的内容为富文本,于是想着得把px像素单位换成我自己的rem

代码如下

let html_str =
	`<p class="" style="padding: 0px; -webkit-font-smoothing: antialiased; list-style: none; margin-bottom: 0px; scrollbar-width: none; font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, Roboto, Ubuntu, &quot;Helvetica Neue&quot;, Helvetica, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, &quot;Source Han Sans CN&quot;, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;; font-size: 15px; line-height: 1.75; color: rgb(5, 7, 59); background-color: rgb(253, 253, 254);">随便写的文字</p>`;

html_str = html_str.replace(/\d+px/g, function(str) {
	let pixel = +str.split('px')[0];
	let rem = pixel * 0.03;
	console.log('转化为响应式单位: ', pixel + '=>' + rem);
	return rem + 'rem';
})
console.log('html_str: ', html_str);

思路:

使用/\d+px/g匹配到数字+px的字符串

replace的第二个参数支持函数,里面可以接收到匹配到的值,利用 'px' 进行分割再转为数字

其中(+)加号为一元加号运算符,位于其操作数之前,可将其操作数转换为数字(如果尚未转换)

最后替换为我这边自己定义的rem单位,我的是1920分辨率下字体大小为33px,20px对应为0.6rem

控制台输出

可以看到已经转换成功

为0的px可以写判断忽略掉,这里就不展示了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值