首页 > 解决方案 > 如何将我的元素放在代码生成器的正确位置

问题描述

大家好,我正在开发像Sketch2Code这样的代码生成器,但我卡在了我的 JSON 上。我想使用myData给定 html 结构的这个示例来创建 HTML 页面。想象这是手绘图像的示例输出,需要放置在 DOM 中。如何将每个元素放置在正确的坐标上?我不想对元素的顶部和左侧使用绝对位置,而是让它与引导网格一起使用

myData = [
  {
    id: 1,
    name: "Image",
    accuracy: 99.92,
    xmin: 122,
    ymin: 115,
    xmax: 275,
    ymax: 241,
    width: 153,
    height: 126
  },
  {
    id: 8,
    name: "Carousel",
    accuracy: 99.75,
    xmin: 223,
    ymin: 289,
    xmax: 867,
    ymax: 481,
    width: 644,
    height: 192
  },
  {
    id: 10,
    name: "Paragraph",
    accuracy: 99.98,
    xmin: 708,
    ymin: 562,
    xmax: 920,
    ymax: 667,
    width: 212,
    height: 105
  },
  {
    id: 10,
    name: "Paragraph",
    accuracy: 99.99,
    xmin: 135,
    ymin: 565,
    xmax: 382,
    ymax: 675,
    width: 247,
    height: 110
  },
  {
    id: 13,
    name: "Button",
    accuracy: 99.83,
    xmin: 206,
    ymin: 688,
    xmax: 345,
    ymax: 746,
    width: 139,
    height: 58
  },
  {
    id: 13,
    name: "Button",
    accuracy: 90.4,
    xmin: 758,
    ymin: 704,
    xmax: 859,
    ymax: 745,
    width: 101,
    height: 41
  }
];

标签: htmljsoncoordinatesgeneratorelement

解决方案


您可以使用动态类和 html 元素。如果您执行以下操作,则上面的示例可以是动态的:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
  </head>
  <body>
    <h1>
      This is a static template, there is no bundler or bundling involved!
    </h1>

    <script>
      const myData = [
        {
          id: 1,
          button: {
            type: "button",
            text: "Click Me!",
            width: 139,
            height: 58,
            pos: {
              top: 100,
              left: 20
            }
          }
        }
      ];

      const body = document.querySelector("body");
      const btn = document.createElement(myData[0].button.type);
      btn.style.position = "absolute";
      btn.innerHTML = `${myData[0].button.text}`;
      btn.style.width = `${myData[0].button.width}px`;
      btn.style.height = `${myData[0].button.height}px`;
      btn.style.top = `${myData[0].button.pos.top}px`;
      btn.style.left = `${myData[0].button.pos.left}px`;
      body.appendChild(btn);
    </script>
  </body>
</html>



推荐阅读