【问题标题】:Use array of background-image urls使用背景图片 url 数组
【发布时间】:2018-04-21 06:27:59
【问题描述】:

在帖子类型的模板中,我有一个自定义标题部分,我想在其中显示多个背景图像。这是单个图像的当前代码:

<div class="single__header" style="background-image: url(../content/uploads/2018/04/fundings-header.jpg); 
background-repeat: no-repeat; 
background-position: center center; 
-webkit-background-size: cover; 
-moz-background-size: cover; 
-o-background-size: cover; 
background-size: cover;">

如何使用/加载多个网址来随机显示不同的背景图片?经过大量搜索,我找到了this solution,但不知何故我无法让它工作。

有什么建议吗?

【问题讨论】:

  • 什么不起作用?您可以发布您的尝试代码以便我们提供帮助吗?
  • @Benoît:我收到一个错误,所以解决方案代码中的某些内容(请点击我上面帖子中的链接)可能不正确。我也试过这个:[链接]stackoverflow.com/questions/49823392/…
  • 错误信息是什么?
  • @Benoît:如果我将标题模板部分中的背景 URL 替换为 background: url(&lt;?php include'functions.php'; displayBackground();?&gt;),则使用带有 &lt;?php get_template_part('components/content/content','header'); ?&gt; 的模板的每个页面都不会显示标题或任何内容,只会显示徽标/顶部的菜单部分。如果我在帖子模板中使用它,我会收到 500 错误。所以我猜解决方案的代码中有些东西是不对的,也许'include'语句是如何使用的?顺便说一句:我确实在“includes”文件夹和“functions.php”中添加了一个带有代码的 background.php 文件。
  • 您可以编辑上面的问题,向我们展示您的 2 个文件的代码吗?

标签: url background-image


【解决方案1】:

不需要额外的 php 文件。 这是一个更优雅的解决方案:

<?php
$imagesDir = 'images/'; //path to your images directory    
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);    
$randomImage = $images[array_rand($images)]; 
?>
<div class="single__header" style="background-image: url(<?= $randomImage ?>); 
background-repeat: no-repeat; 
background-position: center center; 
-webkit-background-size: cover; 
-moz-background-size: cover; 
-o-background-size: cover; 
background-size: cover;">
    Test
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多