我刚刚从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>
&#13;
它在本地html文件中不起作用。它实际上可以在Stackoverflow的代码片段工具中使用,但带有错误消息:
Error:
{
"message": "ReferenceError: makeDiv is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 1,
"colno": 1
}
&#13;
知道我做错了吗?
最好的问候。
答案 0 :(得分: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>