我已经检查了我能找到的所有相关问题,但仍然无法解决,所以我向你们这些可爱的人伸出援手!
我希望我的网站每次有人访问时都有一个随机的颜色背景(多种预先选择的颜色之一)。
有很多次人们要求它调用一个随机的图像,但我只希望有一个块颜色,假设使用粗体背景。
我看到的两个选项以类似的方式使用,但都没有用,它们是:
jQuery(链接:取自汤博乐查询):
1) 在/js/中创建一个新的"background.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) 添加到功能.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(链接):
我把整个字符串放在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; ?>;
}
不幸的是,这两种解决方案似乎都不适合我,而且这两个线程都已过时,因此无法获得进一步的答案,因此无法启动新的线程。
- 有什么想法可以让我在哪里出错吗
- 你认为还有其他方法可以解决这个问题吗
进一步信息:我使用的是超级简单的Less主题,它只附带了3个文件:functions.php、index.php和style.css——我将其作为一个基本主题来完全自定义我自己的主题。
非常感谢!
JavaScript实现的问题是数组索引中有整个CSS声明。此外,由于您将脚本包含在头中,因此需要将代码包装在document.ready处理程序中,并处理WordPress将jQuery放入的noConflict模式。
试试这样的东西:
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
文件中并将其入队,或者将代码放在带有header.php
或操作的head
中。
<style>
<?php
$input = array("#000080", "#00CED1", "#191970");
$rand_key = array_rand($input);
$color = $input[$rand_key];
?>
body {
background: <?php echo $color; ?>;
}
?>
</style>
你不能把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>