无法在本地 html 文件上运行 jsfiddle 代码



我刚刚从jsfiddle复制了一些Javascript代码。

这是我所做的:

<!DOCTYPE html>
<html>
<!-- The function below comes from here: http://jsfiddle.net/redler/QcUPk/8/ -->
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>  -->
<script type="text/javascript">
(function makeDiv(){
    var divsize = ((Math.random()*100) + 50).toFixed();
    var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
    $newdiv = $('<div/>').css({
        'width':divsize+'px',
        'height':divsize+'px',
        'background-color': color
    });
    
    var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
    var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
    
    $newdiv.css({
        'position':'absolute',
        'left':posx+'px',
        'top':posy+'px',
        'display':'none'
    }).appendTo( 'body' ).fadeIn(100).delay(300).fadeOut(200, function(){
       $(this).remove();
       makeDiv(); 
    }); 
})();
</script>
<title>squares with random position</title>
</head>
<body onload="makeDiv()">
</body>
</html>

它在本地 html 文件中不起作用。它实际上在Stackoverflow的代码片段工具中工作,但带有错误消息:

Error:
{
  "message": "ReferenceError: makeDiv is not defined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 1,
  "colno": 1
}

知道我做错了什么吗?

此致敬意。

您已将该函数放入匿名函数中。

将代码更改为以下代码:

  <!DOCTYPE html>
  <html>
  <!-- The function below comes from here: http://jsfiddle.net/redler/QcUPk/8/ -->
  <head>
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <!-- <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>  -->
  <script type="text/javascript">
  function makeDiv(){
      var divsize = ((Math.random()*100) + 50).toFixed();
      var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
      $newdiv = $('<div/>').css({
          'width':divsize+'px',
          'height':divsize+'px',
          'background-color': color
      });
      
      var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
      var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
      
      $newdiv.css({
          'position':'absolute',
          'left':posx+'px',
          'top':posy+'px',
          'display':'none'
      }).appendTo( 'body' ).fadeIn(100).delay(300).fadeOut(200, function(){
         $(this).remove();
         makeDiv(); 
      }); 
  }
  </script>
  <title>squares with random position</title>
  </head>
  <body onload="makeDiv()">
  </body>
  </html>

最新更新