【问题标题】:How do i make a function run every 30 seconds or something?我如何让一个函数每 30 秒运行一次?
【发布时间】:2013-12-15 05:48:19
【问题描述】:

您好,我目前正在让我的背景图片随机出现。但现在我希望它每 30 或 40 秒更改一次图像。现在我的代码如下所示:

#background{
  position: fixed;
  height: 100%;
  width: 100%;
  z-index: -100px;
<?php
  $count = rand(1, 8);
  $hello = "background: url('img/backImg/". $count ."') center center;"; 
  echo ($hello);
?>
  background-repeat:no-repeat;
  background-color:   #d8d8d8;
  background-size: cover;
}

所以我希望$count 字符串每 30 秒取一个随机数。

【问题讨论】:

  • 你需要ajax:w3schools.com/ajax或与php无关的东西。
  • 你需要jquery的ajax或者javascript
  • 服务器上的 PHP 无法做到这一点。您需要发送在浏览器中运行的 javascript 代码。
  • @bozdoz w3schools 是一个糟糕的资源。我推荐jQuery自己的教程。
  • @JanDvorak 别自命不凡。

标签: php html loops web


【解决方案1】:

jQuery Cycle 插件是一个幻灯片插件,支持多种不同类型的过渡效果。它支持悬停暂停、自动停止、自动调整、回调之前/之后、点击触发器等等。

您可以将 timeoutdelay 设置为 30 秒。

【讨论】:

    【解决方案2】:

    您可以在 javascript 的帮助下做到这一点。它会每 30 秒调用一次这个函数

    var myVar=setInterval(function(){myTimer()},30000);
    function myTimer(){
        // your code to change the background image url 
        // you can do that with $('#background').attr('style',"your css") or  
        // $('#background').css('background-url',"your path") 
    }
    

    【讨论】:

      【解决方案3】:
      <pre> 
      <script type="text/javascript">
        $(document).ready(function counter() {
           randomNumber=Math.floor(Math.random() * 8) + 1; //make random number between 1-8
           $(this).css("background-image", "url('img/backImg/" + randomNumber + ".png')");
           setTimeout("counter()",30000); play function counter after 30s
        });//end the $(document).ready
      </script>
      </pre>
      

      试试这个代码,希望对你有帮助。

      此功能在您的页面准备好工作时启动,并生成一个介于 1-8 之间的随机数,然后更改您的背景图像并在 30 秒后执行增益 你只需设置你的而不是 this。

      【讨论】:

        猜你喜欢
        • 2014-03-05
        • 2012-03-26
        • 2011-11-06
        • 2015-01-18
        • 1970-01-01
        • 1970-01-01
        • 2017-10-19
        • 1970-01-01
        • 2021-06-08
        相关资源
        最近更新 更多