风格1随机标签颜色,效果图: 风格2有序循环标签颜色,效果图:
HTML代码:
<html> <head> <meta name="viewport" content="width=device-width" /> <title>纯JS随机/有序生成标签云颜色 - H.W.H</title> <style> body { background: #F9F9F9; } h4 { margin: 0 0 5px 0; background: #F6F6F6; padding: 3px; } #tagcloud { width: 270px; box-shadow: 0 1px 3px rgba(0,0,0,0.2); padding: 10px; background: #FFF; margin: 50px auto; } #tagcloud a { font-size: 12px; opacity: 0.80; filter: alpha(opacity=80); color: #FFF; display: inline-block; margin: 0 5px 5px 0; padding: 0 6px; line-height: 21px; border-radius: 2px; text-decoration: none; } #tagcloud a:hover { background: #F00; } .tags1 { background: #68A2D5; } .tags2 { background: #7DC67D; } .tags3 { background: #E17572; } .tags4 { background: #7898AA; } .tags5 { background: #C35CFF; } .tags6 { background: #33BCBA; } .tags7 { background: #C28F5C; } .tags8 { background: #FF8533; } .tags9 { background: #6E6E6E; } </style> </head> <body> <div id="tagcloud"> <h4>标签云</h4> <a href="#">JavaScript (18)</a> <a href="#">PHP (15)</a> <a href="#">CSS (11)</a> <a href="#">js (8)</a> <a href="#">css (7)</a> <a href="#">php (5)</a> <a href="#">游记 (5)</a> <a href="#">伍珩 (3)</a> <a href="#">Wuheng.Net (3)</a> <a href="#">ruby (3)</a> <a href="#">服务器 (3)</a> <a href="#">读书 (2)</a> <a href="#">javascript (2)</a> <a href="#">前端 (2)</a> <a href="#">rails (2)</a> <a href="#">ruby (2)</a> <a href="#">HTML (2)</a> <a href="#">word-spacing (1)</a> <a href="#">读书 (1)</a> <a href="#">letterSpacing (1)</a> <a href="#">javascript对象 (1)</a> <a href="#">disabled (1)</a> <a href="#">jQuery (1)</a> <a href="#">大帅哥 (1)</a> <a href="#">正则 (1)</a> </div> </body> </html>
【风格1】js代码:
<script type="text/javascript"> window.onload = function() { /*风格1:标签颜色是随机生成的*/ var tags_main = document.getElementById('tagcloud'); var tags_a = tags_main.getElementsByTagName('a'); var tags_style_num = 9;//样式数量 for(var i=0; i<tags_a.length; i++){ var rand = parseInt(Math.random()*tags_style_num+1); tags_a[i].className = 'tags'+rand; } }; </script>
【风格2】js代码:
<script type="text/javascript"> window.onload = function() { /*风格2:标签颜色是按顺序生成的*/ var tags_main = document.getElementById('tagcloud'); var tags_a = tags_main.getElementsByTagName('a'); var tags_style_num = 9;//样式数量 var color_list= []; for(var k=0; k<tags_a.length/tags_style_num; k++){ for(var j=1; j<tags_style_num+1; j++){ color_list.push(j); } } for(var i=0; i<tags_a.length; i++){ tags_a[i].className = 'tags'+color_list[i]; } }; </script>