<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>获取随机颜色</title>
<!-- 引入线上jquery文件 -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<style type='text/css'>
a{
width:150px;
height:150px;
line-height:150px;
display: inline-block;
font-size:12px;
margin-left:10px;
border-radius:50%;
text-align:center;
text-decoration:none;
}
a:hover{
cursor:pointer;
}
button{
width:80px;
height:30px;
line-height:30px;
margin-left:10px;
margin-top:10px;
border:none;
}
p{
width:150px;
text-align:center;
}
</style>
<script type='text/javascript'>
// 随机数 函数
function Rand(min,max){
return Math.floor(Math.random() * (max - min + 1) );
}
// 随机背景色 函数
function randRGB(){
return 'rgb(' + Rand(0,255) + ',' + Rand(0,255) + ',' + Rand(0,255) + ')';
}
$(document).ready(function(){
var rand_rgb = '';
// 遍历a标签
$('a').each(function(){
// 调用随机背景色并赋值给rand_rgb
rand_rgb = randRGB();
// 设置背景 并 显示背景 值
$(this).css('backgroundColor',rand_rgb).text(rand_rgb);
// 添加hover效果
$(this).hover(
function(){
$(this).stop().animate({'fontSize':'18px','borderRadius':'30px','boxshadow':'0px 0px 30px' + rand_rgb},500);
},function(){
$(this).stop().animate({'fontSize':'12px','borderRadius':'50%','boxshadow':'none'},500);
}
);
// 添加点击效果
$(this).click(function(){
// 调用随机背景色并赋值给rand_rgb
rand_rgb = randRGB();
// 设置a标签背景 并 显示背景 值
$(this).css('backgroundColor',rand_rgb).text(rand_rgb);
});
});
//遍历button标签
$('button').each(function(val){
// 添加点击效果
$(this).click(function(){
// 调用随机背景色并赋值给rand_rgb
rand_rgb = randRGB();
// 设置a标签背景 并 显示背景 值
$(this).parents('div').children('a').css('backgroundColor',rand_rgb).text(rand_rgb);
});
});
});
</script>
</head>
<body>
<div><a>1</a><p><button>随机颜色</button></p></div>
<div><a>2</a><p><button>随机颜色</button></p></div>
<div><a>3</a><p><button>随机颜色</button></p></div>
<div><a>4</a><p><button>随机颜色</button></p></div>
<div><a>5</a><p><button>随机颜色</button></p></div>
</body>
</html>