Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:没有带requestAnimationFrame动画的代码?_Javascript - Fatal编程技术网

Javascript:没有带requestAnimationFrame动画的代码?

Javascript:没有带requestAnimationFrame动画的代码?,javascript,Javascript,我正在学习Javascript并测试下面书中的代码。它应该为图像设置动画,但不会。我使用alert添加打印输出,它显示函数只执行一次。出了什么问题 <!doctype html> <html> <head> <title> My home page </title> <script> var cat = document.querySelector("img"); var angle = 0, lastTime =

我正在学习Javascript并测试下面书中的代码。它应该为图像设置动画,但不会。我使用alert添加打印输出,它显示函数只执行一次。出了什么问题

<!doctype html>
<html>
<head>
  <title> My home page </title>
  <script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
  //alert(count);
  //++count;
  if (lastTime != null)
    angle += (time - lastTime) * 0.001;
  lastTime = time ;
  cat.style.top = (Math.sin(angle) * 20) + "px";
  cat.style.left = (Math.cos(angle) * 200) + "px";
  requestAnimationFrame(animate);
}
  </script>
</head>
<body>
  <p style ="text-align: center">
    <img src ="img/cat.jpg" style ="position: relative">
  </p >
</body>
<script>requestAnimationFrame(animate);</script>
</html>

谢谢您的帮助。

如果您查看控制台,您将看到cat未定义

这是因为var cat=document.querySelectorimg;在head元素中运行,因此img还不存在

如果你把代码移到正文的末尾,它就会起作用。 或者,可以在触发DOMContentLoaded事件时运行代码

我的主页

var cat=document.querySelectorimg; var angle=0,lastTime=null; var计数=0; 函数动画时间{ //警报计数; //++计数; 如果lastTime!=null 角度+=时间-上次时间*0.001; lastTime=时间; cat.style.top=Math.sinangle*20+px; cat.style.left=Math.cosangle*200+px; 请求动画帧动画; } 请求动画帧动画; 当浏览器看到标记时,他停止呈现页面,并在其中运行代码

因此,代码中的问题是,行var cat=document.querySelectorimg;在img附加到文档之前发生,因此查询将一无所获

您需要做的唯一更改是移动var cat=document.querySelectorimg;在身体下面,像这样:

</body>
<script>
    var cat = document.querySelector("img");
    requestAnimationFrame(animate);
</script>

</html>