2016-11-27 30 views
3

目前,我正在使用静态CSS使用类似于下面显示的代码的方法执行此操作。使我的网站上的每个href都变成不同的颜色

#main-content > article.mh-loop-item.clearfix.post-95.post.type-post.status-publish.format-standard.has-post-thumbnail.hentry.category-singles.tag-kxngg-jxnes-italy > div > header > h3 > a { 
color: blue; 
} 
#main-content > article.mh-loop-item.clearfix.post-93.post.type-post.status-publish.format-standard.has-post-thumbnail.hentry.category-singles.tag-aquil-eddie-guerrero > div > header > h3 > a { 
color: red; 
} 

和每个后ID它产生不同的颜色为歌曲名显示为,我想怎么过做一些更先进的JavaScript或东西的时候曾经有一个一href与某个类相关联,它会为该链接生成一个随机颜色。

+3

您的HTML和JavaScript在哪里? –

+0

@ScottMarcus就是这样,我现在只用CSS就可以做到这一点,它非常混乱......我的CSS文件看起来像完全癌症,因为它会产生大约15种颜色的ID,以某些数字开始。 – Placeholder

+1

为什么你想要打破这样的可用性?人们使用链接的颜色和外观进行导航。让颜色随机对用户不会有帮助。 – junkfoodjunkie

回答

7

它可以通过jQuery的如下

$(document).ready(function(){ 
 
    
 
    $('body a').each(function(){ 
 
    var color = 'rgb(' + randomNumber() + ',' + randomNumber() + ',' + randomNumber() + ')'; 
 
    $(this).css("color", color); 
 
    }); 
 
    
 
    function randomNumber(){ 
 
    return Math.floor(256*Math.random()); 
 
    } 
 
    
 
});
<a href="javascrip:void(0)">First link</a> 
 
<a href="javascrip:void(0)">Second link</a> 
 
<a href="javascrip:void(0)">Third link</a> 
 
<a href="javascrip:void(0)">Fourth link</a> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

+0

这是完美的! – Placeholder

2

好吧,如果你真的想这样做(不明白为什么,但我喜欢它:-))。然后我会告诉你一个方法。我将使用jquery,但随时可以即兴创作。

创建或编辑您的JavaScript文件。并按照沿(我假设你的文章标题有类称为postTitle)

$('.postTitle').each(function() { 
    var red = Math.floor(Math.random() * 256); 
    var green = Math.floor(Math.random() * 256); 
    var blue = Math.floor(Math.random() * 256); 
    $(this).css("color", "rgb(" + red + "," + green + "," + blue + ")"); 
}) 
+0

这是非常有用的感谢,现在搞乱它。 – Placeholder

4

像这样的工作来实现,请试试看:

/*I just hard coded everything*/ 
 
var yourClass = "article", 
 
    hs = Array.from(document.querySelectorAll('a.' + yourClass)), 
 
    colors = ['blue', 'red', 'green', 'purple', 'black', 'blue', 'yellow', 'lime']; 
 

 
hs.forEach(function(elm) { 
 
    elm.style.color = colors[Math.floor(Math.random() * colors.length)]; 
 
})
<a href="#"> normal </a> 
 

 
<a class="article" href="#"> title1 </a> 
 
<a class="article" href="#"> title2 </a> 
 
<a class="article" href="#"> title3 </a> 
 
<a class="article" href="#"> title4 </a>

+0

好的答案,因为这一个给OP选项来预定义颜色 –

+0

谢谢@GustvandeWal – RizkiDPrast

相关问题