使用 JavaScript 增加上/左/下/右值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12115258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using JavaScript to increment top/left/bottom/right values
提问by day0
I am trying to increment the position of an element by, say, xpixels. Here is what I've tried so far:
我正在尝试通过x像素来增加元素的位置。这是我迄今为止尝试过的:
var top = document.getElementById("something").style.top;
top = top + "300px"
I know that this is not going to work, but I was wondering if it was possible to increment a position value like this.
我知道这行不通,但我想知道是否可以增加这样的位置值。
采纳答案by jfriend00
Because style.top
is a string with units on the end of it like "300px"
you can only do math with it when you convert just the numeric part to an actual number.
因为style.top
是一个末尾带有单位的字符串,就像"300px"
您只能在将数字部分转换为实际数字时才能使用它进行数学运算。
Assuming you have a positioned element (so setting the top
value will do something) and you already have a top
style set directly on the element and not set via CSS (so getting obj.style.top
will actually get you something), you can do it by parsing the number out of the style value like this:
假设您有一个定位元素(因此设置top
值会做一些事情)并且您已经top
在元素上直接设置了样式而不是通过 CSS 设置(因此获取obj.style.top
实际上会为您提供一些东西),您可以通过解析数字来完成像这样的样式值:
var obj = document.getElementById("something");
var topVal = parseInt(obj.style.top, 10);
obj.style.top = (topVal + 300) + "px";
Working example: http://jsfiddle.net/jfriend00/pt46X/
回答by Some Guy
That won't work fine because, for example, if top
had a value of 200px
, it would become "200px300px"
. Try this:
这将无法正常工作,因为例如,如果top
值为200px
,它将变为"200px300px"
。试试这个:
var elem = document.getElementById("something");
elem.style.top = parseInt(elem.style.top, 10) + 300 + "px"
回答by user12269102
let top = 0;
let left = 0;
let text = document.getElementById("TextToTranslate");
text.setAttribute("style","top:"+top+"px; "+left+":px;");
use this in a while loop and it works fine, i'm just figuring out how to slow it down so i can see the transition
在 while 循环中使用它,它工作正常,我只是想知道如何减慢它的速度,以便我可以看到过渡