使用 JavaScript 实现网站标签随机颜色原理很简单,通过 random 与 floor 获取一个随机数,然后从数组里面的颜色值中选择相应的颜色,这里我设置了 12 个随机颜色,当然你也可以自行添加更多颜色,修改一下参数即可。具体 JavaScript 代码如下:
- <script type=“text/javascript”>
- len = $(“.widget_ui_tags .items a”).length – 1;
- $(“.widget_ui_tags .items a”).each(function(i) {
- var let = new Array( ’27ea80′,’3366FF’,’ff5473′,’df27ea’, ’31ac76′, ‘ea4563′, ’31a6a0’, ‘8e7daa’, ‘4fad7b’, ‘f99f13’, ‘f85200’, ‘666666’);
- var random1 = Math.floor(Math.random() * 12) + 0;
- var num = Math.floor(Math.random() * 5 + 12);
- $(this).attr(‘style’, ‘background:#’ + let[random1] + ‘; opacity: 0.6;’+”);
- if ($(this).next().length > 0) {
- last = $(this).next().position().left
- }
- });
- </script>
.widget_ui_tags .items a 是我目前所使用的主题标签侧边栏所对应的样式名,下面会给出具体样式,你可以直接将其改成自己的样式名。opacity 设置透明度,这里我设置的是 0.6 ,具体效果如下:
上图对应的 CSS 样式如下:
- /** 热门标签样式 **/
- .widget_ui_tags .items {
- overflow: hidden;
- padding: 15px 0 12px 15px;
- }
- .widget_ui_tags .items a {
- color: #FFF;
- background-color: #f6f6f6;
- float: left;
- width: 30%;
- margin: 1%;
- padding: 3px;
- font-size: 12px;
- height: 28px;
- line-height: 22px;
- overflow: hidden;
- text-align:center;
- border-radius: 5px;
- }
- .widget_ui_tags .items a:hover {
- color: #fff;
- background-color: #45B6F7;
- border: 1px solid #FFF;
- opacity:1 !important;
- }
虽然这里说是用 JS 实现网站标签随机颜色,但是其实你可以将代码略作调整适用于任何你想随机改变颜色的地方。
以上内容整理自@蝈蝈要安静