腾讯云服务器优惠活动华纳云香港服务器

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

使用 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实现网站标签随机颜色?-第1张-boke112百科(boke112.com)

上图对应的 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 实现网站标签随机颜色,但是其实你可以将代码略作调整适用于任何你想随机改变颜色的地方。

以上内容整理自@蝈蝈要安静

本文地址:https://boke112.com/post/5095.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu