用随机图像填充表格 [英] Fill table with random images

查看:110
本文介绍了用随机图像填充表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我的编码经验包括修改简单的脚本以在我的页面上工作。其次,我搜索并发现了几个类似的问题,但不能完全按照我的方式工作。



我需要一些帮助来填充具有随机图像的3x3表格大约40个图像的阵列。我目前有一个使用backgroundImage属性的工作模板。我想将其更改为使用常规图像而不是背景图像,以便最终添加模态图像。

我假设这行代码是需要更改的元素。



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

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

随机插入图像到使用JavaScript的表格



从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);


函数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 =600height =600border =1id =mainTable>
< tr>
< td width =200class =cellid =cell1>& nbsp;< / td>
< td width =200class =cellid =cell2>& nbsp;< / td>
< td width =200class =cellid =cell3>& nbsp;< / td>
< / tr>
< tr>
< td width =200class =cellid =cell4>& nbsp;< / td>
< td width =200id =cell5>标题< / td>

< / tr>

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


解决方案

如果您有多个对象,请遵循以下准则: / p>


  • 将多个对象放在不同的组中。


    • ex。图片网址= 9个字符串/表格单元= 5 < td>

    • >如果任何一个团体都可以减少的话。


      • ex。所有9个字符串的路径都是images / Image _

      • ex。最后一个单元格没有 .cell 类别,并且没有获得图像。

      • 将每个组收集到一个HTMLCollection或一个数组中,并根据需要存储变量中排除的内容。


        • ex。 var base =images / Image _ var imgs = ['01.jpg','02.jpg',...'09.jpg ']

        • 前。 var cellArray = Array.from(document.querySelectorAll('。cell'))


        • 通过 for 循环或Array方法运行其中一个数组,并在每次迭代中运行一个函数,该函数将两个数组操作为所需的结果。


          • ex。查看演示




        在下面的演示中,重构函数 randomCellBG()它将采用给定数量的图像文件名( imgs [] )和它们所在的路径()。只要它们位于同一位置,此功能就会接受任意数量的文件名称。如果您希望使其更具多功能性,可以将目标表作为参数,并将单元格数组更改为< td> ,而不是 .cell 类。



        详情请参阅演示

        ⍟注释与OP的代码具体相关b
        $ b

        Demo



          / *一组数字,每个都表示||每个图像的url的独特部分⍟var imgs = ['01.jpg',... '09 / jpg'] demo demo中的数组是一个数字(不含引号)的数组,但OP中的数组是字符串(每个都被引用)* / var imgs = [1,2,3,4,5,6,7,8,9]; / *每个图像url具有共同的部分⍟var base ='images /图片_'* / var base ='https://placehold.it/100x100/000/fff?text=';function randomCellBG(base,imgs){//参考< table> var T = document.getElementById('mainTable'); / *将所有.cell收集到NodeList中并转换为||它变成一个数组* / var cellArray = Array.from(T.querySelectorAll('。cell')); // map()数组;在每个循环中运行一个函数... cellArray.map(function(cel,idx){//获取一个随机数1  -  9 var ran = Math.round(Math.random()* imgs.length); / * Concatenate基础和随机数形成一个图像的URL字符串结果:images / Image_08.jpg* / var img = base + ran.toString(); / *将该url指定为| |在当前迭代中.cell ||的backgroundImage属性* / cel.style.backgroundImage ='url('+ img +')';});} //调用randomCellBGrandomCellBG(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 =300height =200border =1id =mainTable> < TR> < td width =100class =cellid =cell1>& nbsp;< / td> < td width =100class =cellid =cell2>& nbsp;< / td> < td width =100class =cellid =cell3>& nbsp;< / td> < / TR> < TR> < td width =100class =cellid =cell4>& nbsp;< / td> < td colspan ='2'id =cell5>标题< / td> < / TR> < / table>< / body>< / html>

        First, my coding experience consists of modifying simple scripts to work on my pages. Second, I have searched and found several similar questions, but can't quite work my way through them.

        I need some assistance with populating a 3x3 table with random images from an array of approximately 40 images. I currently have a working template that makes use of the backgroundImage property. I would like to change it to use regular images instead of background images so I can eventually add modal images.
        I assume that this line of code is what needs to changed

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

        I've tried several options I've found here and elsewhere. These two links seem the most relevent, but I can't quite seem to pull them together.

        Randomly inserting images into table using Javascript

        show random image from array in javascript

        Any assistance or if there is a better solution that I can be directed to will be greatly appreciated.

        <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>  
        

        解决方案

        When you have multiple objects, follow these guidelines:

        • Place multiple objects in separate groups.
          • ex. urls of images = 9 strings / table cells = 5 <td>
        • If any of the groups could be reduced do so.
          • ex. All 9 strings have a path of "images/Image_"
          • ex. The last cell doesn't have a class of .cell and it doesn't get an image.
        • Gather each group into an HTMLCollection or an array and store what's excluded in a variable if it's needed.
          • ex. var base = "images/Image_" var imgs = ['01.jpg','02.jpg',...'09.jpg']
          • ex. var cellArray = Array.from(document.querySelectorAll('.cell'))
        • Run one of the arrays through a for loop or an Array method and on each iteration, run a function that will manipulate both arrays into the desired result.
          • ex. See demo

        In the following demo is the refactored function randomCellBG() it will take a given array of image file names (imgs[]) and the path that they are located (base). This function will accept any amount of file names as long as they are in the same location. If you'd like to make it more versatile, you could make the target table a parameter and change the array of cells as <td> instead of .cell classes.

        Details are commented in demo

        ⍟ notes that specifically pertain to OP's code

        Demo

        /* 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>

        这篇关于用随机图像填充表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆