<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>jquery获取随机颜色</title> <script type="text/javascript" src="jquery-3.3.1.min.js"></script> <style type="text/css"> a{ float: left; display: block; margin:50px; width: 100px; line-height: 100px; text-align: center; height: 100px; color: #fff; border-radius: 50px; text-decoration: none; } </style> <script type="text/javascript"> //改变标签的背景颜色 function aa(tag){ var len=document.getElementsByTagName('a').length console.log(len) for (var i = 0 ; i<len; i++) { document.getElementsByTagName(tag)[i].style.backgroundColor ='rgb('+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+')' } } $(document).ready(function(){ aa('a') $('a').mouseover(function(){ $bg=$(this).css('backgroundColor') $(this).css('box-shadow','0px 0px 20px '+$bg) $(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>
总结和理解:
刚开被这句话卡主了,
var len=document.getElementsByTagName(tag).length 。因为之前学的都是document.getElementsByTagName( )这里面传的标签。我就把里面改成了
document.getElementsByTagName('a')标签。也可以正常使用。加上console.log(len) 发现2个取出来的都是4,明白了,传入tag指的是所有的标签的个数。
新知识点:
Math.random () 方法获取一个随机值,获取到的是0到-1的值。再使用Math.floor()方法,如果出现小数就进行四舍五入变成整数。
这也是目前我们第1个js和jq配合使用的小案例,受益匪浅。