发表于: 2019-07-23 20:55:51

1 1157


今天完成了什么:

完成第一个按钮按下去让盒子变色。

var divblue = document.getElementsByTagName("div")[0];

console.log(Action);

找到第一个盒子



var Action = document.getElementsByTagName("button")[0];
console.log(Action);
Action.onclick = function () {
divblue.style.background="blue";

}

按下第一个button按钮使盒子变蓝色


var Action = document.getElementsByTagName("button")[1];
console.log(Action);
Action.onclick = function () {
divblue.style.background="orange";
}
按下第二个button按钮使盒子变回橙色,但是如果变回原来的颜色还不会。


遇到了什么问题:

暂无


今天收获了什么:

成功点击按钮让第一个盒子变颜色,后面继续看看咋整把;

整理了下js需要学习到的技能导图;




js随机颜色的生成方法

网页中颜色的使用方式有一下几种
**1、颜色名称 **,如red black white
2、十六进制颜色,网页中常用,每两位代表红绿蓝的值的比例, 如 #ffffff白色 #000000黑色
3、rgba颜色, 如 rgba(255,255,255,0.5) 半透明白色 ,此方式ie8及以下不兼容
RGBA(R,G,B,A)
R:红色值。正整数 | 百分数
G:绿色值。正整数 | 百分数
B:蓝色值。正整数 | 百分数
A:Alpha透明度。取值0~1之间。
4、hsla颜色值, 如 hsla(360, 50%, 50%, .5) 半透明红色 , 此方式ie8及以下不兼容
HSLA(H,S,L,A)
H:Hue(色调)。0(或360)表示红色,120表示绿色,240表示蓝色,也可取其他数值来指定颜色。取值为:0 - 360
S:Saturation(饱和度)。取值为:0.0% - 100.0%
L:Lightness(亮度)。取值为:0.0% - 100.0%
A:Alpha透明度。取值0~1之间。

方法一(随机RGB颜色值)#####


//颜色对象
function Color() {
this.r = Math.floor(Math.random() * 255);
this.g = Math.floor(Math.random() * 255);
this.b = Math.floor(Math.random() * 255);
this.color = 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',0.8)';
}


方法二 (生成十六进制的颜色值)

随机生成6个字符然后再串到一起,闭包调用自身与三元运算符让程序变得内敛,初心者应该好好学习这种写法。

var getRandomColor = function () {
return '#' + (function (color) {
return (color += '0123456789abcdef' [Math.floor(Math.random() * 16)]) && (color.length == 6) ? color : arguments.callee(color);
})('');
}
方法三


var getRandomColor = function () {
return (function (m, s, c) {
return (c ? arguments.callee(m, s, c - 1) : '#') + s[m.floor(m.random() * 16)]
})(Math, '0123456789abcdef', 5)
}
把Math对象,用于生成hex颜色值的字符串提取出来,并利用第三个参数来判断是否还继续调用自身。

方法四

这个要求我们对数组做些扩展,map将返回一个数组,然后我们再用join把它的元素串成字符。


以下为引用的内容Array.prototype.map = function (fn, thisObj) {
var scope = thisObj || window;
var a = [];
for (var i = 0, j = this.length; i < j; ++i) {
a.push(fn.call(scope, this[i], i, this));
}
return a;
};
var getRandomColor = function () {
return '#' + '0123456789abcdef'.split('').map(function (v, i, a) {
return i > 5 ? null : a[Math.floor(Math.random() * 16)]
}).join('');
}

方法五
var getRandomColor = function () {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}

这个实现非常逆天,虽然有点小bug。我们知道hex颜色值是从#000000到#ffffff,后面那六位数是16进制数,相当于“0x000000”到“0xffffff”。这实现的思路是将hex的最大值ffffff先转换为10进制,进行random后再转换回16进制。

方法六

基本方法5的改进,利用左移运算符把0xffffff转化为整型。这样就不用记16777215了。由于左移运算符的优先级比不上乘号,因此随机后再左移,连Math.floor也不用了。

var getRandomColor = function () {
return '#' + (Math.random() * 0xffffff << 0).toString(16);
}




明天计划:

写任务;



 


返回列表 返回列表
评论

    分享到