如何在Javascript中设置表格单元格的背景图片?

时间:2019-04-19 22:34:52

标签: javascript css sapui5 sap

我目前正在通过CSS在动态sap.m.table中静态设置背景图像。但是,我想用Javascript而不是CSS设置背景图像。例如,给定这样的图像数组:

 var imgArray = imageUrl1, imageUrl2, imageUrl3, imageUrl4. 

我想遍历数组并将表的单元格分配给imageUrls。

我目前正在CSS中执行以下操作:

.sapMListTblCell:nth-child(2) {
    background-image: url("https://image.shutterstock.com/image-photo/cute-baby-tabby-short-hair-260nw-160585535.jpg");
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
}

这里是jsbin的链接,描述了我如何创建表:https://jsbin.com/huyiyofexu/edit?html,css,js,output

1 个答案:

答案 0 :(得分:1)

有多种方法可以执行此操作,但是我建议从表中创建2d数组,然后根据行和列数执行您喜欢的任何逻辑对其进行迭代:

const bgs = [
  ["red", "green", "blue"],
  ["magenta", "yellow", "cyan"],
  ["black", "gray", "white"]
];

document.addEventListener("DOMContentLoaded", () => {
  const myTable = document.getElementById("MyTable");
  
  const trs = Array.from(myTable.querySelectorAll("tr"));
  const grid = trs.map((tr) => {
    const tds = Array.from(tr.querySelectorAll("td"));
    return tds;
  }); 


  grid.forEach((row, rowNum) => {
    row.forEach((tdElement, colNum) => {
      tdElement.style.background = bgs[rowNum][colNum];
    });
  });
});
td {
  height: 100px;
  width: 100px;
  text-align: center;
}
<table id="MyTable">
  <tr>
    <td>1-1</td>
    <td>1-2</td>
    <td>1-3</td>
  </tr>
  <tr>
    <td>2-1</td>
    <td>2-2</td>
    <td>2-3</td>
  </tr>
  <tr>
    <td>3-1</td>
    <td>3-2</td>
    <td>3-3</td>
  </tr>
</table>