使用setInterval更新.style属性

时间:2016-12-17 02:11:43

标签: javascript html css

我试图以设定的间隔移动div元素的位置,但是setInterval方法执行一次然后停止。 setInterval()不会按预期每200毫秒重复更新.style.transform。

<!DOCTYPE html>
<html>
<head>
<title>Snake game</title>
<style type="text/css">
  .container {
    width: 500px;
    height: 500px;
    border: 2px solid black;
  }

  #snakehead {
    width: 5px;
    height: 5px;
    background: pink;
    position: relative;
    left: 0px;
}
</style>
<script type="text/javascript" src="snake.js"></script>
</head>
<body>
  <div class="container">
    <div id="snakehead"></div>
  </div>
</body>
</html>

Javascript:理想情况下,我也希望能够使用vx和vy向任何方向移动蛇头。无论如何将这些值放入.style.transform = translateX()?

function snakepos() {
    var x = 0;
    var y = 0;
    var vx = 1;
    var vy = 0;
    return {
        move: function() {
                x += vx;
                y += vy;
                var snakehead = document.querySelector("#snakehead");
                snakedhead.style.left = "5px";
        }
    };
}

window.onload = function() {
    console.log("hi");
    var container = document.querySelector(".container");
    var snake = snakepos();

    setInterval(function() {
        snake.move();
    }, 200);
}

我知道在使用.css的jQuery中可以更轻松地完成这项工作,但我想知道如何在vanilla javascript中完成此操作。先感谢您。

2 个答案:

答案 0 :(得分:0)

snakehead.style.left = (snakedhead.style.left + "5px"); 

snakehead.style.left = (snakedhead.style.left - "5px"); 

答案 1 :(得分:0)

我推荐一种比我更熟悉的风格的东西:

function snakepos() {
  this.x = 0;
  this.y = 0;
  this.vx = 1;
  this.vy = 1;
  this.snakehead = document.querySelector("#snakehead");
  var me = this;
  this.move = function() {
    me.x += me.vx;
    me.y += me.vy;
    me.snakehead.style.top = me.y + "px";
    me.snakehead.style.left = me.x + "px";
  };

  return this;
}

  console.log("hi");
  var container = document.querySelector(".container");
  var snake = new snakepos();

  setInterval(function() {
    snake.move();
  }, 200);

请参阅小提琴:https://jsfiddle.net/theredhead/td8opb0b/1/