<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>获取随机色</title> <script type="text/javascript" src="jquery-3.3.1.min.js"></script> <style> body{width: 800px;text-align: center;margin: 10px auto;} 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; } div{width: 100px;height: 50px;margin: 50px auto;} button{display: block;width: 100%;height: 100%;line-height: 50px; } </style> </head> <body> <a href="#">1</a> <a href="#">2</a> <a href="#">3</a> <a href="#">4</a> <div><button type="button">点我变色</button></div> </body> <script> $(function(){ myChange(); }) function myChange(){$.each($('a'),function(){ var randomColor = 'rgb('+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+')'; var randomNum =Math.floor(Math.random()*101); $(this).css('backgroundColor',randomColor); $(this).text(randomNum); })} $('button').click(myChange); </script> </html>
------效果图--------
总结:
jquery和js可以实现混编,jquery的$.each()更为简单