Hi!请登陆

如何用JavaScript实现网站标签随机颜色?

2021-2-11 41 2/11

使用 JavaScript 实现网站标签随机颜色原理很简单,通过 random 与 floor 获取一个随机数,然后从数组里面的颜色值中选择相应的颜色,这里我设置了 12 个随机颜色,当然你也可以自行添加更多颜色,修改一下参数即可。具体 JavaScript 代码如下:

  1. <script type="text/javascript">
  2.     len = $(".widget_ui_tags .items a").length - 1;
  3.     $(".widget_ui_tags .items a").each(function(i) {
  4.         var let = new Array( '27ea80','3366FF','ff5473','df27ea', '31ac76', 'ea4563', '31a6a0', '8e7daa', '4fad7b', 'f99f13', 'f85200', '666666');
  5.         var random1 = Math.floor(Math.random() * 12) + 0;
  6.         var num = Math.floor(Math.random() * 5 + 12);
  7.         $(this).attr('style', 'background:#' + let[random1] + '; opacity: 0.6;'+'');
  8.         if ($(this).next().length > 0) {
  9.             last = $(this).next().position().left
  10.         }
  11.     });
  12. </script>

.widget_ui_tags .items a 是我目前所使用的主题标签侧边栏所对应的样式名,下面会给出具体样式,你可以直接将其改成自己的样式名。opacity 设置透明度,这里我设置的是 0.6 ,具体效果如下:

如何用JavaScript实现网站标签随机颜色?

上图对应的 CSS 样式如下:

  1. /** 热门标签样式 **/
  2. .widget_ui_tags .items {
  3.     overflow: hidden;
  4.     padding: 15px 0 12px 15px;
  5. }
  6. .widget_ui_tags .items a {
  7.     color: #FFF;
  8.     background-color: #f6f6f6;
  9.     float: left;
  10.     width: 30%;
  11.     margin: 1%;
  12.     padding: 3px;
  13.     font-size: 12px;
  14.     height: 28px;
  15.     line-height: 22px;
  16.     overflow: hidden;
  17.     text-align:center;
  18.     border-radius: 5px;
  19. }
  20. .widget_ui_tags .items a:hover {
  21.     color: #fff;
  22.     background-color: #45B6F7;
  23.     border: 1px solid #FFF;
  24.     opacity:1 !important;
  25. }

虽然这里说是用 JS 实现网站标签随机颜色,但是其实你可以将代码略作调整适用于任何你想随机改变颜色的地方。

内容整理自:蝈蝈要安静 - http://blog.quietguoguo.com/2462.html

相关推荐