jq获取随机颜色案例

原创2018-11-09 18:18:4098
摘要:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>jq获取随机颜色</title> <script src="jquery-3.3.1.min.js"></script&
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jq获取随机颜色</title>
<script src="jquery-3.3.1.min.js"></script>
<style>
a{
float: left;
margin: 50px;
width: 100px;
display: block;
line-height: 100px;
color: #000;
text-align: center;
height: 100px;
border-radius: 50px;
text-decoration: none;
}
</style>
<script>
function bg (tag) {
// body... 
var len = document.getElementsByTagName(tag).length //获取长度。
for (var i = 0; i<len ; i++) {
// 随机rgb写法 Math.floor(Math.random()*256)

 document.getElementsByTagName(tag)[i].style.backgroundColor='rgb('+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+')' //你少了一个拼接符 “+”//length返回数组中元素的数目
}

}
$(document).ready(function(){
bg('a')
$('a').mouseover(function(){
$bgc=$(this).css('backgroundColor')
$(this).css('box-shadow','0px 0px 20px'+$bgc)
$(this).css('border-radius','20px')
})
$('a').mouseleave(function(){

$(this).css('box-shadow','none')
$(this).css('border-radius','50px')
})
})
</script>
</head>

<body>
<a href="#">1</a>
<a href="#">2</a>
<a href="#">3</a>
<a href="#">4</a>

</body>
</html>

获取标签名数组:getElementsByTagName

随机rgb写法 Math.floor(Math.random()*256)

总结:通过获取标签名数组,来获取a标签的长度。再根据长度使用for循环遍历就能同时修改所有a标签参数。再使用jq的鼠标移上 移出事件改变css。这个案例就完成了

批改老师:天蓬老师批改时间:2018-11-09 21:40:46
老师总结:你的思路是正确的,仔细想一下,是否还有更简便的实现方法呢?

发布手记

热门词条