如何将innerHTML中的两个元素对齐?

时间:2020-03-05 14:23:02

标签: javascript html

我认为span将使元素对齐,但是该按钮出现在p元素下方。

for (let i = 0; i < arr.length; i++) {
  main.innerHTML += `
  <span>
    <p onclick="border(${i})">${arr[i].name}</p>
    <button>Delete</button>
  </span>`
}

2 个答案:

答案 0 :(得分:2)

p元素是Block-level element,您可以将 display 属性设置为inline-block

演示:

var arr = [{name: "test"}]
var main = document.getElementById("main");
for (let i = 0; i < arr.length; i++) {
  main.innerHTML += `
  <span>
    <p onclick="border(${i})" style="display:inline-block">${arr[i].name}</p>
    <button>Delete</button>
  </span>`;
}
<div id="main"></div>

答案 1 :(得分:1)

如果您要内联pbutton,请按照以下说明将pspan交换。 您还可以查看我的摘录

document.addEventListener("DOMContentLoaded", () => {
  let main = document.querySelector('body');
  let arr = [{name: 'first'},{name: 'second'}];

  for (let i = 0; i < arr.length; i++) {
       main.innerHTML += `
                  <p>
                  <span onclick="border(${i})">${arr[i].name}</span>
                  <button>Delete</button>
                  </p>
                  `;
  }
});
<!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>Document</title>
</head>
<body> 
</body>
</html>