在Wordpress中创建随机背景颜色

时间:2015-02-24 23:32:49

标签: javascript php jquery css wordpress

我已经查看了我能找到的所有相关问题,但仍然无法让这个问题发挥作用,所以我可以向你们寻求可爱的人!

我希望每次有人访问时,我的网站都会有一个随机颜色背景(多种预选颜色中的一种)。

有很多时候人们要求它调用随机图像,但我只是希望有一个块颜色,假设使用粗体背景。

我所看到的两种选择以类似的方式使用,但无济于事,是:

jQuery(link:取自Tumblr查询):

1)创建一个新的' background.js'文件在/ js /中,代码为:

    <script>
    var bgcolorlist=new Array("background: #ff871b", "background: #15efa1", "background: #51ddff", "background: #ff1b6c", "background: #000000");
    var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
    $('body').css('backgroundColor', color);
</script>

2)添加到function.php:

add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_enqueue_script(
        'your-script', // name your script so that you can attach other scripts and de-register, etc.
        get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
        array('jquery') // this array lists the scripts upon which your script depends
    );
}

&安培; PHP和CSS(link):

我将整个字符串放在style.css文件中:

<?php
$input = array("#000080", "#00CED1", "#191970");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
body {
background: <?php echo  $color; ?>;
}

不幸的是,这些解决方案似乎都不适用于我,并且两个线程都已过时,因此无法获得更多答案,因此开始了一个新线程。

  1. 关于我可能出错的地方的任何想法?
  2. 你认为其他任何方法都是解决问题的更好方法吗?
  3. 更多信息:我使用的是超级简单Less theme,它只附带3个文件:functions.php,index.php和style.css - 我将其用作裸机骨骼主题完全自定义我自己的主题。

    非常感谢提前!

2 个答案:

答案 0 :(得分:2)

JavaScript实现的问题在于您在数组索引中拥有完整的CSS声明。此外,由于您将脚本包含在头部,因此需要将代码包装在document.ready处理程序中,并处理noConflict mode WordPress puts jQuery in

尝试这样的事情:

jQuery(function($) {
    var bgcolorlist=["#ff871b", "#15efa1", "#51ddff", "#ff1b6c", "#000000"];
    var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
    $('body').css('backgroundColor', color);
});

PHP在CSS文件中不起作用的原因是因为.css文件通常不运行PHP代码。您需要将其放在单独的.php文件中并将其排入队列,或将代码放入head header.php或操作中。

<style>
<?php
$input = array("#000080", "#00CED1", "#191970");
$rand_key = array_rand($input);
$color = $input[$rand_key];
?>
body {
    background: <?php echo $color; ?>;
}
?>
</style>

答案 1 :(得分:0)

您不能将PHP放在CSS文件中,因此如果您想使用PHP方法,则需要在标题中回显本地CSS块。

例如,在你的functions.php文件中:

function getBgColor() {
    $input = array("#000080", "#00CED1", "#191970");
    return $input[rand(0, count($input) - 1)];
}

然后在你的header.php中:

<style>
    body {
        background: <?php echo getBgColor(); ?>;
    }
</style>