循环随机背景图像

时间:2015-08-31 08:34:34

标签: php jquery html

我想要显示一个随机的背景图像,它会在五秒后开始一个随机的其他背景图像循环。

首先我为我的背景图片创建了一个数组:

<?php
  $bg = array('bg1.jpg', 'bg2.jpg', 'bg3.jpg', 'bg4.jpg', 'bg5.jpg', 'bg6.jpg', 'bg7.jpg', 'bg8.jpg', 'bg9.jpg', 'bg10.jpg', 'bg11.jpg');
  $i = rand(0, count($bg)-1);
  $selectedBg = "$bg[$i]";
?>

第二次我在我的身上贴了一张随机图片:

<style>
 @media screen and (min-width: 600px) {
    body {
      background-image: url(<?php bloginfo('template_url'); ?>/images/backgrounds/<?php echo $selectedBg; ?>);
    }
 }
</style>

现在我想使用phpjQuery来选择其他随机图片并更改背景。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

如果你想每5秒循环你的背景图像(没有用户重新加载页面),你不能在PHP上做,它必须在客户端(Javascript)完成。

PHP是一种生成HTML代码的工具,该代码将在用户的浏览器上呈现,但之后无法更改页面,这就是javascript的用途。

<script type="text/javascript">

    // declare list of backgrounds
    var images = ['bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg'];

    // declare function that changes the background
    function setRandomBackground() {
        // choose random background
        var randomBackground = images[Math.floor(Math.random() * images.length)];

        // set background with jQuery
        $('body').css('background-image', 'url("images/' + randomBackground + '")');
    }

    // declare function that sets the initial background, and starts the loop.
    function startLoop() {
        // Set initial background.
        setRandomBackground();

        // Tell browser to execute the setRandomBackground every 5 seconds.
        setInterval(setRandomBackground, 5 * 1000);
    }

    // One the page has finished loading, execute the startLoop function
    $(document).ready(startLoop);

</script>

答案 1 :(得分:0)

尝试使用less和js之类的:

    var timeout = 1000;      
    var action = function() {    
        var random = Math.floor(Math.random() * 6) + 1 ;
        if(random.length<=1){random = '0'+random;}
        var wynikLos = 'path/to/file/bg-'+random+'.jpg';
        less.modifyVars({
          '@img': wynikLos
        });
        setTimeout(action, timeout);
    };
    action();

在Less:

body{background-image:@img;}

http://lesscss.org/

P.S。 未经测试

相关问题