JS【实战】CSS 样式相关的处理

CSS 样式键转换

如 fontSize -> font-size

// 函数封装 -- CSS样式键转换,如 fontSize -> font-size
function CSSformatKey(oldKey) {
  // 查找所有大写字母,转换为 "-小写"
  const newKey = oldKey.replace(/[A-Z]/g, (c) => `-${c.toLocaleLowerCase()}`);
  return newKey;
}
let oldKey = 'fontSize';
let result = CSSformatKey(oldKey);
console.log(result);

CSS 样式单位转换

px 转 vw

// 函数封装 -- CSS样式单位转换,如 375px -> 100vw
function px2vw(components = []) {
  // 正则匹配 '10px' '9.5px',并对数值分组
  const reg = /^(\d+(\.\d+)?)px$/;
  components.forEach((component) => {
    const props = component.props || {};
    // 遍历组件的属性
    Object.keys(props).forEach((key) => {
      const val = props[key];

      // 非字符串无需转换;
      if (typeof val !== 'string') {
        return;
      }
      // 无px则无需转换
      if (reg.test(val) === false) {
        return;
      }
      // 取得匹配的分组,第1项为匹配的所有内容,如375px,第2项为匹配到的px前的数值,如375
      const arr = val.match(reg) || [];
      // 提取出数值部分
      const numStr = arr[1];
      // 将字符串数值转换为数字
      const num = parseFloat(numStr);
      // 因UI图的画布宽度是 375px,即100vw = 375px 则px 转 vw 的公式为  100vw = 375px/375*100
      const vwNum = (num / 375) * 100;
      // 避免无法除尽,保留两位小数
      props[key] = `${vwNum.toFixed(2)}vw`;
    });
  });
}

let components = [
  {
    props: {
      height: '100px',
    },
  },
  {
    props: {
      height: '140px',
    },
  },
];
px2vw(components);
console.log(components);

结果为:

[ { props: { height: '26.67vw' } }, { props: { height: '37.33vw' } } ]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝阳39

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值