0

我有以下代码,它使文本在单击时爆炸。但我需要让它在 5 秒后爆炸。它必须自动启动,无需点击。有人可以告诉我我必须改变什么吗?

<script type="text/javascript">
function fx(o) {
  var $o = $(o);

  $o.html($o.text().replace(/([\S])/g, "<span>$1</span>"));
  $o.css("position", "relative");
  $("span", $o).each(function(i) {
    var newTop = Math.floor(Math.random()*500)*((i%2)?1:-1);
    var newLeft = Math.floor(Math.random()*500)*((i%2)?1:-1);

    $(this).css({position: "relative",
      opacity: 1,
      fontSize: 50,
      top: 0,
      left: 0
    }).animate({
      opacity: 0,
      fontSize: 90,
      top: newTop,
      left:newLeft
    },1200);
  });
} </script>

<span onclick="fx(this)"><h1>Text Here</h1> </span>
4

2 回答 2

2

将您的功能更改fx为:

function fx(o) {
  setTimeout (
    function () {
      var $o = $(o);

      $o.html($o.text().replace(/([\S])/g, "<span>$1</span>"));
      $o.css("position", "relative");
      $("span", $o).each(function(i) {
        var newTop = Math.floor(Math.random()*500)*((i%2)?1:-1);
        var newLeft = Math.floor(Math.random()*500)*((i%2)?1:-1);

        $(this).css({position: "relative",
          opacity: 1,
          fontSize: 50,
          top: 0,
          left: 0
        }).animate({
          opacity: 0,
          fontSize: 90,
          top: newTop,
          left:newLeft
        },1200);
      });
    },
    5000
  );
}

这会将执行延迟 5 秒(使用setTimeout函数)。

https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout

于 2013-01-22T11:10:24.080 回答
2

用户 setTimeout()

<script type="text/javascript">
    function fx(o) {
      setTimeout(function(){var $o = $(o);

      $o.html($o.text().replace(/([\S])/g, "<span>$1</span>"));
      $o.css("position", "relative");
      $("span", $o).each(function(i) {
        var newTop = Math.floor(Math.random()*500)*((i%2)?1:-1);
        var newLeft = Math.floor(Math.random()*500)*((i%2)?1:-1);

        $(this).css({position: "relative",
          opacity: 1,
          fontSize: 50,
          top: 0,
          left: 0
        }).animate({
          opacity: 0,
          fontSize: 90,
          top: newTop,
          left:newLeft
        },1200);
      });
    },5000);
    } </script>
于 2013-01-22T11:10:33.477 回答