在js中制作一个十行十列的表格,要求每个单元格随机变色

JavaScript016

在js中制作一个十行十列的表格,要求每个单元格随机变色,第1张

onload = function(){

    var tab = document.createElement("table")

    tab.style.margin = "0 auto"

    tab.style.width = "500px"

    var tb = document.createElement("tbody")

    tab.appendChild(tb)

    for(var i = 0 i < 10 i++){

        var row = tb.insertRow(tb.rows.length)

        for(var j = 0 j < 10 j++){

            var col = row.insertCell(row.cells.length)

            col.style.width = "50px"

            col.style.height = "50px"

            var a = Math.floor(Math.random() * 255)

            var b = Math.floor(Math.random() * 255)

            var c = Math.floor(Math.random() * 255)

            col.style.backgroundColor = "rgb(" + a + "," + b + "," + c + ")"

        }

    }

    document.body.appendChild(tab)

}

分别命名图片名字为 "1.jpg","2.jpg","3.jpg"...等,然后使用Math.random()*图片数目,再使用,var src_id=parseInt(Math.random()*图片数目)将随即得到的数字变成整数,这样,就可以使用var src=src_id+"jpg"来得到图片的名称(当然也可以拼凑出图片SRC地址),然后利用image对象改变图像的SRC值为随机获得的src值。并且设置该脚本为页面载入时自动运行,就可以使图片在每次刷新网页时随即显示了。

至于获得单元格对象,可以使用document.getElementById("单元格ID"),也可以使用,document.getELementByName('单元格name'),获得此对象后就简单多了吧?以后的操作就是获得单元格里图像对象

创建三个类名,三个类名分别给上三个背景颜色,如:

.bgColor0{background-color:#158AEA}

.bgColor1{background-color:#996633}

.bgColor2{background-color:#66FF00}

获取012三个随机数前面添加字符串'bgColor'就得到随机的类名,然后给相应的元素添加得到的随机类名就行了。

而要获取012三个随机数就用Math.floor(Math.random()*3)获取。

不过你要求背景色不能重复,那么就把三个类名放进一个数组里。已经使用的类名就用”数组名.shift“把它从数组中弹出。然后剩下的两个类名就要获取01两个随机数,就用Math.floor(Math.random()*2)获取0和1其中一个数。

剩下的你知道该怎么做了。