我已经检查了我能找到的所有相关问题,但仍然无法使其发挥作用,因此我正在与你们可爱的人们联系!
我希望我的网站在每次有人访问时都有随机颜色背景(多种预选颜色之一)。
人们多次要求它调用随机图像,但我只是希望有一个 block 颜色,假设使用粗体背景。
我见过以类似方式使用但无济于事的两个选项是:
jQuery(link:取自 Tumblr 查询):
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)添加到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; ?>;
}
不幸的是,这些解决方案似乎都不适合我,并且两个线程都已过时,因此无法获得进一步的答案,因此启动一个新线程。
- 对于我可能会出错的地方有什么想法吗?
- 您认为还有其他更好的方法来解决这个问题吗?
更多信息:我正在使用 super 简单的 Less theme ,它只附带 3 个文件:functions.php、index.php 和 style.css - 我将其用作基本主题来完全自定义我自己的主题。
非常感谢!
最佳答案
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>
关于javascript - 在 WordPress 中创建随机背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28708463/