获取一个样式值的数字WITHOUT“px;”后缀 [英] Get a number for a style value WITHOUT the "px;" suffix
问题描述
我在Javascript和HTML中制作了一个RTS游戏。听起来雄心勃勃我知道,但我不是在这里拍摄星星。只是有点东西让我娱乐。
I am making a RTS game in Javascript and HTML. Sounds ambitious I know but I'm not shooting for the stars here. Just a little something to keep me entertained.
我目前正在游戏的运动部分。我有一个运动引擎应该工作,但有一个问题。在我的脚本中,我使用不等式语句(>
和<$ c)将绝对定位字符的当前左和顶值与其目标$ c>< )。问题是,我得到 document.getElementById(nameVar).style.left
的反馈是一个字符串的形式(例如 200px
)不是数字(例如
200
),因此比较不起作用。
I am currently working on the movement part of the game. I have a movement engine that should work, but there is a problem. In my script I compare the current left and top values of an absolutely positioned character to those of its target (which may be moving) using inequality statements (>
and <
). The problem is that the feedback I get form document.getElementById(nameVar).style.left
is in the form of a string (e.g. 200px
) not a number (e.g. 200
), so the comparisons don't work.
我的问题是,有什么办法把字符串变成一个数字,我可以操纵我想要的方式?
My question is, is there any way to turn the string into a number that I can manipulate the way I want to? Either by using an altered address or by preforming some procedure with the feedback once I get it.
任何帮助将是巨大的。
推荐答案
parseInt
为您提供数值:
var tmp = parseInt(document.getElementById(nameVar).style.left, 10);
console.log(tmp);
或者,如@PeteWilson在注释中建议的,使用 parseFloat
or, as @PeteWilson suggests in the comments, use parseFloat
这篇关于获取一个样式值的数字WITHOUT“px;”后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!