【问题标题】:Fill table with random images用随机图像填充表格
【发布时间】:2017-11-19 23:25:57
【问题描述】:

首先,我的编码经验包括修改简单的脚本以在我的页面上工作。其次,我搜索并发现了几个类似的问题,但无法完全解决它们。

在使用大约 40 个图像的数组中的随机图像填充 3x3 表时,我需要一些帮助。我目前有一个使用 backgroundImage 属性的工作模板。我想将其更改为使用常规图像而不是背景图像,以便最终添加模态图像。
我假设这行代码需要更改

cell1.style.backgroundImage = "url("+images[imagePos]+")";

我已经尝试了几个在这里和其他地方找到的选项。这两个链接似乎最相关,但我似乎无法将它们放在一起。

Randomly inserting images into table using Javascript

show random image from array in javascript

如果有任何帮助或有更好的解决方案可以指导我,我们将不胜感激。

<html>
<head>
<title>Random BG Table</title>
<style>
.cell {
    background-position: center;
} 
</style>
<script>

var images = new Array();
    images.push("images/Image_01.jpg");
    images.push("images/Image_02.jpg");
    images.push("images/Image_03.jpg");
    images.push("images/Image_04.jpg");
    images.push("images/Image_05.jpg");
    images.push("images/Image_06.jpg");
    images.push("images/Image_08.jpg");
    images.push("images/Image_09.jpg");


function randomCellBG()
{
    var cell1 = document.getElementById("cell1");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell1.style.backgroundImage = "url("+images[imagePos]+")";

    var cell2 = document.getElementById("cell2");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell2.style.backgroundImage = "url("+images[imagePos]+")";

    var cell3 = document.getElementById("cell3");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell3.style.backgroundImage = "url("+images[imagePos]+")";

    var cell4 = document.getElementById("cell4");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell4.style.backgroundImage = "url("+images[imagePos]+")";

    cell5.style.backgroundColor = "gray"


}
</script>

</head>

<body onLoad="randomCellBG()"><br><br><br>
<table width="600" height="600" border="1" id="mainTable">
  <tr>
    <td width="200" class="cell" id="cell1">&nbsp;</td>
    <td width="200" class="cell" id="cell2">&nbsp;</td>
    <td width="200" class="cell" id="cell3">&nbsp;</td>
  </tr>
  <tr>
    <td width="200" class="cell" id="cell4">&nbsp;</td>
    <td width="200"  id="cell5">title</td>

  </tr>

</table>
</body>
</html>  

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    使用 innerHTML 属性

    function randomCellBG()
    {
        var cell1 = document.getElementById("cell1");
        var imagePos = Math.round(Math.random()*(images.length-1));
        cell1.innerHTML = "<img src='"+images[imagePos]+"' />";
    
        var cell2 = document.getElementById("cell2");
        var imagePos = Math.round(Math.random()*(images.length-1));
        cell1.innerHTML = "<img src='"+images[imagePos]+"' />";
    
        var cell3 = document.getElementById("cell3");
        var imagePos = Math.round(Math.random()*(images.length-1));
        cell1.innerHTML = "<img src='"+images[imagePos]+"' />";
    
        var cell4 = document.getElementById("cell4");
        var imagePos = Math.round(Math.random()*(images.length-1));
        cell1.innerHTML = "<img src='"+images[imagePos]+"' />";
    
        cell5.style.backgroundColor = "gray";   
    }
    

    【讨论】:

      【解决方案2】:

      当您有多个对象时,请遵循以下准则:

      • 将多个对象放在不同的组中。
        • 例如。图片的网址 = 9 个字符串/表格单元格 = 5 &lt;td&gt;
      • 如果可以减少任何组,请这样做。
        • 例如。所有 9 个字符串的路径均为 "images/Image_"
        • 例如。最后一个单元格没有 .cell 类,也没有图像。
      • 将每个组收集到一个 HTMLCollection 或一个数组中,并在需要时将排除的内容存储在一个变量中。
        • 例如。 var base = "images/Image_"var imgs = ['01.jpg','02.jpg',...'09.jpg']
        • 例如。 var cellArray = Array.from(document.querySelectorAll('.cell'))
      • 通过for 循环或Array 方法运行其中一个数组,并在每次迭代中运行一个函数,将两个数组操作为所需的结果。
        • 例如。查看演示

      在下面的演示中是重构函数randomCellBG(),它将采用给定的图像文件名数组(imgs[])和它们所在的路径(base)。只要它们位于同一位置,此函数将接受任意数量的文件名。如果您想让它更通用,您可以将目标表作为参数并将单元格数组更改为&lt;td&gt; 而不是.cell 类。

      详情在demo中注释

      ⍟ 特别与 OP 代码相关的注释

      演示

      /* An array of numbers, each reresenting the 
      || unique part of each image's url
      ⍟ var imgs = ['01.jpg', ... '09/jpg']
      ⍟ The array in demo is an array of numbers (no quotes)
      ⍟ but the one in OP is an array of strings (each are quoted)
      */
      var imgs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      
      /* The part of what each image url has in common
      ⍟ var base = 'images/Image_'
      */
      var base = 'https://placehold.it/100x100/000/fff?text=';
      
      
      function randomCellBG(base, imgs) {
      
        // Reference the <table>
        var T = document.getElementById('mainTable');
      
        /* Collect all .cell into a NodeList and convert
        || it into an array
        */
        var cellArray = Array.from(T.querySelectorAll('.cell'));
      
        // map() the array; run a function on each loop...
        cellArray.map(function(cel, idx) {
      
          // Get a random number 1 - 9
          var ran = Math.round(Math.random() * imgs.length);
      
          /* Concatenate base and random number to form
          || a string of a url of an image
          ⍟ result: "images/Image_08.jpg"
          */
          var img = base + ran.toString();
      
          /* Assign that url as the value to the 
          || backgroundImage property of the .cell
          || in current iteration
          */
          cel.style.backgroundImage = 'url(' + img + ')';
      
        });
      
      }
      
      // Call randomCellBG
      randomCellBG(base, imgs);
      .cell {
        background-position: center;
      }
      
      td {
        background-color: grey
      }
      <!doctype html>
      <html>
      
      <head>
        <title>Random BG Table</title>
      
      </head>
      
      <body><br><br><br>
        <table width="300" height="200" border="1" id="mainTable">
          <tr>
            <td width="100" class="cell" id="cell1">&nbsp;</td>
            <td width="100" class="cell" id="cell2">&nbsp;</td>
            <td width="100" class="cell" id="cell3">&nbsp;</td>
          </tr>
          <tr>
            <td width="100" class="cell" id="cell4">&nbsp;</td>
            <td colspan='2' id="cell5">title</td>
      
          </tr>
      
        </table>
      </body>
      
      </html>

      【讨论】:

      • 有没有办法将图像 1-9 命名为 01-09?它目前似乎只有在我放弃前导零时才有效。这没什么大不了的,就像我喜欢给图像命名一样。
      • 对不起,我必须强调该数组是 数字数组(无引号),您的数字用零填充,因此您需要换行每个都用引号引起来,因为它们被认为是字符串
      • 我尝试添加引号,但没有成功。我一定错过了别的东西。现在是时候修复随机函数以消除重复了
      • 您的带有 cmets 的代码完全无法理解。不知道为什么,但是当我将“更改为”时它起作用了。另外,我将 .jpg 设置为附加到字符串的变量,从而使 url 使我的数组更干净。
      • 双引号到单引号是否适合您?这很奇怪。好吧,如果它解决了您的问题,请不要忘记接受和/或赞成这个答案。编码愉快。
      【解决方案3】:

      除了将图片设置为单元格的背景外,您还可以通过JS创建一个元素并使用'appendChild'函数将元素插入单元格中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-03
        • 2011-03-23
        • 2013-12-23
        • 1970-01-01
        • 2020-05-14
        • 2016-07-22
        • 2016-03-28
        • 1970-01-01
        相关资源
        最近更新 更多