简体   繁体   English

将JavaScript变量设置为边距

[英]Setting a javascript variable to margins

How do I make the left margin a variable so that I can make it change dynamically on the keydown of the arrows 如何使左边距成为变量,以便可以在箭头的键按下时对其进行动态更改

I'm trying to make the div called tank move. 我正在尝试使称为tank的div移动。

Code: 码:

function moveTank() {
  var tank = document.getElementById("tank");
  var tankLeft = tank.style.margin-left;    
}

moveTank();
var tankLeft = tank.style.marginLeft;

Note: It will work only for inline specified margin - <img id="tank" src="..." style="margin-left:10px"> 注意:仅适用于行内指定的边距- <img id="tank" src="..." style="margin-left:10px">

And why not to use position:absolute with left and top for your tank sprite? 为何不为您的坦克精灵使用position:absolutelefttop

<div id="tankfield" style="position:relative">
  <img id="tank" src="..." style="position:absolute;left:0px;top:0px">
</div>
<script>
  var tankX=0, tankY=0;
  function placeTank() {
    var tank = document.getElementById("tank");
    tank.style.left = tankX+'px';
    tank.style.top  = tankY+'px';
  }
  // ...
  function tankDown() {
    tankY += 5;
    placeTank();
  }
  // ...
</script>

Hyphenated style attributes get camelCased in js, so you want tank.style.marginLeft . 连字符的样式属性在js中获得camelCased,因此您需要tank.style.marginLeft

Also note that 1) That method will only read style attributes set directly on the element, not those in a stylesheet, and 2) it will be a string, either "" or else something like "123px" 另请注意,1)该方法将只读取直接在元素上设置的样式属性,而不能读取样式表中的样式属性; 2)将是字符串,可以是“”或“ 123px”之类的字符串

why are you using margin? 你为什么要使用保证金? just move the tank with left/top position: 只需以左/上位置移动水箱即可:

try tank.css({left: "-=10px"}); 试试tank.css({left: "-=10px"});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM