猿问

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

我以为 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>`

}


米脂
浏览 102回答 2
2回答

拉风的咖菲猫

p元素是块级元素,可以设置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>

有只小跳蛙

如果你想拥有p并button内联,只需交换,p就像span我在下面所做的那样。你也可以查看我的截图document.addEventListener("DOMContentLoaded", () => {&nbsp; let main = document.querySelector('body');&nbsp; let arr = [{name: 'first'},{name: 'second'}];&nbsp; for (let i = 0; i < arr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp;main.innerHTML += `&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span onclick="border(${i})">${arr[i].name}</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button>Delete</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; `;&nbsp; }});<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <meta http-equiv="X-UA-Compatible" content="ie=edge">&nbsp; &nbsp; <title>Document</title></head><body>&nbsp;</body></html>
随时随地看视频慕课网APP

相关分类

Html5
我要回答