基础学习: es6 模板字符串 tag template

一个类似于 styled components 的效果
更新于: 2023-09-11 09:33:17

效果

Document

hello world

问题

实现这个效果
如何用js实现:
const htmlElement = document.createElement('div');
htmlElement.styles = `
    color: red;
    background: white;
`

es6模板字符串

const obj = {
  name: 'aric',
  age: 100
};
const str = `I am ${obj.name}, ${obj.age} old years old`;

带 tag 的

const obj = {
  name: "aric",
  age: 100,
};
const str = tag`I am ${obj.name}, ${obj.age} old years old`;

function tag() {
  console.log("args: ", arguments);
}

完整的实现代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1 id="heading-target">hello world</h1>
    <script>
      function str2styleObj(str) {
        const styleObj = {};
        const styleArr = str.split(";");
        styleArr.forEach((item) => {
          const [key, value] = item.split(":");
          if (value) {
            styleObj[key.trim()] = value.trim();
          }
        });
        return styleObj;
      }

      HTMLElement.prototype.styles = function (styles) {
        const styleObj = str2styleObj(styles[0]);
        Object.assign(this.style, styleObj);
      };

      const el = document.querySelector("#heading-target");
      el.styles`
        color: red;
        line-height: 1.5;
        font-size: 48px;
      `;
    </script>
  </body>
</html>

参考