【问题标题】:Extract the different css transformations from a transform string?从转换字符串中提取不同的 css 转换?
【发布时间】:2020-03-23 21:19:38
【问题描述】:

这是一个示例 CSS 转换字符串:

rotate(-10 50 100)
translate(-36 45.5)
skewX(40)
scale(1 0.5)

从这个字符串我想要么

  • 为每个转换获取一个字符串
  • 获取具有我可以访问的属性的对象

我该怎么做?

我最好的想法是使用 RegEx,但我还没有找到一个可行的 RegEx 解决方案:

[a-z]+?\([\-a-z0-9\s]*?\)

https://regex101.com/r/Ycjuxz/1

也欢迎您对不使用 RegEx 的解决方案提出不同的想法。

【问题讨论】:

  • \n分割,然后使用RegExp获取函数名和参数值。
  • @Teemu:还不够。它只是使用换行符的示例字符串。我认为 css 转换的规范也允许使用不同的空格。此外,您的解决方案也会在每个参数之间中断。
  • @user1283776 你如何获得 CSS 转换字符串(在你的例子中)?你能举个例子吗?
  • @Richard:本页顶部的示例是 CSS 转换字符串的示例:developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform。我只是使用 querySelector(element).getAttribute("transform") 将转换字符串作为字符串获取。我不知道还有什么更聪明的方法可以使用。
  • 不由自主地选择了\w+\(.*\),鉴于您的示例,这似乎工作正常。

标签: javascript css regex css-transforms


【解决方案1】:

一个快速示例,说明如何使用正则表达式执行此操作并将结果简化为对象:

function parseTransform(transform) {
    return Array.from(transform.matchAll(/(\w+)\((.+?)\)/gm))
        .reduce((agg, [, fn, val]) => ({
            ...agg,
            [fn]: val
        })
        , {});
}

const res = parseTransform(`rotate(-10 50 100)
translate(-36 45.5)
skewX(40)
scale(1 0.5)`);

这个的输出是

{rotate: "-10 50 100", translate: "-36 45.5", skewX: "40", scale: "1 0.5"}

在这个版本中,如果函数出现两次,我们将覆盖该函数的值。如果某些属性可以出现多次,您可以将它们合并在一起。

【讨论】:

  • 谢谢!但它没有给出这个合理字符串的正确答案:“translate(200 200) skewX(40)”。也许如果你稍微修改一下? "(\w+)((.+?))"
  • @user1283776 是的,好点!谢谢。我已更新我的答案以反映这一变化。
【解决方案2】:

基于 Teemu 的评论:

const text=`rotate(-10 50 100)
translate(-36 45.5)
skewX(40)
scale(1 0.5)`;
const rows = text.split('\n');
const transformations = rows.reduce((acc, cur) => {
  const key = cur.substring(0, cur.indexOf('('));
  const value = cur.replace(key, '').replace('(', '').replace(')', '');
  acc[key] = value;
  return acc
}, {});

console.log(transformations);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多