我之前问过一个问题 - HERE - 关于如何将边框颜色设置为随机颜色。我有这个工作。
如您所见,我的数组中可能有 7 种颜色。我如何编辑我的代码,以便一旦选择了一种颜色,就不会重复使用它。我的页面上有 3 个 div 将使用颜色,所以我想要 7 种可能的颜色中的 3 种不同的颜色。
我如何使用它的完整代码:
<div id="featured-posts" class="container_12">
<?php
global $post;
$myposts = get_posts('numberposts=3&category=12');
foreach($myposts as $post) :
?>
<?php global $post; ?>
<?php
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );
?>
<?php
$colors = array("#000000", "#949c51", "#571c1e", "#f36533", "#782a80", "#f6a41d", "#ed1b24");
$randomColor = $colors[array_rand($colors)];
?>
<a href="<?php the_permalink(); ?>">
<div class="grid_4 featured-home" style="background: url(<?php echo $src[0]; ?> ) !important;">
<div class="featured-details" style="border-color: <?php echo $randomColor; ?>;">
<h4 style="color: <?php echo $randomColor; ?>;"><?php the_title(); ?></h4>
<p><?php the_excerpt(); ?> <q style="color: <?php echo $randomColor; ?>; font-weight:bold !important;">Read more ></q></p>
</div>
<div class="featured-lower" style="border-color: <?php echo $randomColor; ?>;"></div>
</div></a>
<?php endforeach; ?>
</div>
最佳答案
你可以 shuffle然后 pop每次离开数组的最后一个元素:
定义一次颜色数组(这需要从循环中删除):
$colors = array("#000000", "#949c51", "#571c1e", "#f36533", "#782a80", "#f6a41d", "#ed1b24");
然后每次你使用 randomColor 时,你都会将它洗牌并删除要使用的数组的最后一个元素:
shuffle($colors);
$randomColor = array_pop($colors);
关于html - 随机颜色 CSS - 防止使用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13693957/