效果預覽:
源碼分享:<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } #box{ width: 300px; border: 1px solid #d5d5d5; padding: 10px; margin: 100px auto; overflow: hidden; } #box a{ display: block; float: left; height: 30px; line-height: 30px; padding: 0 10px; color: #fff; background: #000; margin: 0 10px 10px 0; text-decoration: none; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; font-family: "Microsoft YaHei"; } </style></head><body><div id="box"> <a href="#">Java</a> <a href="#">Css</a> <a href="#">HTML</a> <a href="#">JavaScript</a> <a href="#">前端優化</a> <a href="#">前端開發</a> <a href="#">Java</a> <a href="#">Css</a> <a href="#">HTML</a> <a href="#">JavaScript</a> <a href="#">前端優化</a> <a href="#">前端開發</a> <a href="#">Java</a> <a href="#">Css</a> <a href="#">HTML</a> <a href="#">JavaScript</a> <a href="#">前端優化</a> <a href="#">前端開發</a></div><script> window.onload = function () { //獲取節點 var oBox = document.getElementById('box'); var aList = oBox.getElementsByTagName('a'); for(var i=0;i<aList.length;i++) { //設置背景顏色 aList[i].style.background = randColor(); }; console.log(randColor()); }; //隨機色方法 function randColor() { var colors = Math.floor(Math.random() * (255 * 255 * 255)); colors = colors.toString(16); if( colors.length < 6 ) { colors = '0'+colors; } return '#'+colors; };</script></body></html>