发表于: 2019-10-21 23:23:08
1 877
今天完成的事情:
1.任务一实现了点击变色,每次变3个。暂未实现延迟函数
明天的事情:
1.完成任务一,并思考代码过程。为什么会是这样,为何要这样用。
遇到的问题和收获:
1.Math对象
Math 对象用于执行数学任务。
Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math()。
使用Math时,
Math.random()
是取0~1之间的随机数,不包括1,
Math.floor(Math.random()
是往下取最接近的整数,如生成1.01,则取1。
实现九宫格,首先我写了随机获得颜色,用rgb的方式,取3个随机值,乘以256意思是将0~1的范围扩大到0~256,不包括256,即最大为255,将3个随机数值分别分配到r,g,b内。
function getColor() {
var rgb;
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
rgb = "rgb(" + r + "," + g + "," + b + ")";
return rgb;
}
随后需要随机生成3个盒子。将Math乘以9,得到0~8的随机数,将值赋予定义出的3个盒子,由于需要3个盒子颜色都不同,所以需要一个if函数进行判断,只有当盒子1、盒子2和盒子3的颜色值都不相同时,才会赋予3个盒子随机的背景颜色。否则就重新走一遍取色流程。
document.getElementById("begin").onclick = function getBox() {
var one = Math.floor(Math.random() * 9);
var two = Math.floor(Math.random() * 9);
var three = Math.floor(Math.random() * 9);
var box = document.getElementsByTagName("li");
cm();
if (one !== two && two !== three && three !== one) {
box[one].style.backgroundColor = getColor();
box[two].style.backgroundColor = getColor();
box[three].style.backgroundColor = getColor();
} else getBox();
};
由于我还没有做延时,所以暂时用点击实现。每次点击时,前面显示的3个颜色需要消失,再出现新的颜色。这里是使用了
function cm() {
var li = document.getElementsByTagName("li"); //抓取所有“li"标签,赋值数组li
for (var i = 0; i < li.length; i++) { //历遍所有li标签,改变backgroundColor
li[i].style.backgroundColor = "rgb(235,147,22)";
}
}
定义出一个函数,用getElementByTagName抓取所有的li标签,用for循环把所有的li标签颜色都改为默认的、从未点击时的颜色。并将这个函数放在盒子每次取色之前。实现每次点击都出现新的3个格子颜色。
这个任务说实话挺懵比的。很多东西看不懂,实际上这么用了也可能不是特别清楚原理。学到了Math的取0~1随机数的用法,floor的用法,if和for的使用以及获取id的getElementById和获取标签的getElementByTagName。
但毕竟万事开头难,js和css不同,继续学习吧。
评论