发表于: 2018-09-09 20:15:53
1 735
今天完成的事情
看了math.round和math.random,定时器
连写带抄的基本完成了js任务一
明天计划的事情
继续看js基础知识,看看任务二相关的知识点
遇到的问题
各种函数方法不会写,连不到一起,随机获取盒子和颜色还不是很能理解操作
收获
1.for循环,感觉挺重要的,看着简单,用起来还挺复杂。如果希望一遍又一遍地运行相同的代码,并且每次的值都不同,那么使用循环是很方便的。
for (语句 1; 语句 2; 语句 3)
{
被执行的代码块
}
语句 1 在循环(代码块)开始前执行
语句 2 定义运行循环(代码块)的条件
语句 3 在循环(代码块)已被执行之后执行
若想让循环停止下来,就要附加条件if(){break;}
2for/in 语句循环遍历对象的属性:
var cars={
name:"BMW",
country:"Germany",
age:123
};
for(keys in cars){
console.log(keys)
}
3.Math.round()把数四舍五入为最接近的整数。var a= Math.round(0.99);
Math.radom()返回 0 ~ 1 之间的随机数。var a= Math.round();
Math.floor向下取整数
Math.cell向上取整数
4.定时器 setTimeou("function();",delaytime);倒计时定时器
setInterval("function();",delaytime);循环定时器
第一个参数“function()”是定时器触发时要执行的动作,而第二个参数“delaytime”则是间隔的时间,以毫秒为单位,即填写“5000”,就表示5秒钟。 倒计时定时器是在指定时间到达后触发事件,而循环定时器就是在间隔时间到来时反复触发事件,两者的区别在于:前者只是作用一次,而后者则不停地作用。
清除定时器:clearTimeout(对象) 清除已设置的setTimeout对象
clearInterval(对象) 清除已设置的setInterval对象
5.任务一的思路
(1)九个盒子随机获取三个:
function getBox() {
var box = document.getElementsByClassName("box");
for (var i = 0; i < 1000; i++) {
var box1 = Math.floor(Math.random() * 9);
var box2 = Math.floor(Math.random() * 9);
var box3 = Math.floor(Math.random() * 9);
if (box1 !== box2 && box1 !== box3 && box2 !== box3) {
break;
}
}
}
(2)给获取到的三个盒子改变颜色
box[box1].style.backgroundColor = changeColor();
box[box2].style.backgroundColor = changeColor();
box[box3].style.backgroundColor = changeColor();
function changeColor() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b +")";
}
(3)获取三个盒子改变颜色后九个盒子恢复橙色
function resent() {
var box = document.getElementsByClassName("box");
for (var i = 0; i < 9; i++) {
box[i].style.backgroundColor = "orange";
}
}
(4)设置定时器
var time;
function twinkle() {
time = setInterval(getBox(), 1000);
}
function stop() {
clearInterval(time);
resent();
}
评论