jQuery / Javascript - 如何将像素值 (20px) 转换为数值 (20)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3024084/
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
jQuery / Javascript - How do I convert a pixel value (20px) to a number value (20)
提问by John Himmelman
I know jQuery has a helper method for parsing unit strings into numbers. What is the jQuery method to do this?
我知道 jQuery 有一个辅助方法可以将单位字符串解析为数字。什么是 jQuery 方法来做到这一点?
var a = "20px";
var b = 20;
var c = $.parseMethod(a) + b;
回答by Andy E
No jQuery required for this, Plain Ol' JS (tm)will do ya,
不需要 jQuery,Plain Ol' JS (tm)就可以,
parseInt(a, 10);
回答by Roly
More generally, parseFloatwill process floating-point numbers correctly, whereas parseIntmay silently lose significant digits:
更一般地,parseFloat将正确处理浮点数,而parseInt可能会默默地丢失有效数字:
parseFloat('20.954544px')
> 20.954544
parseInt('20.954544px')
> 20
回答by unomi
var c = parseInt(a,10);
回答by just somebody
$.parseMethod = function (s)
{
return Number(s.replace(/px$/, ''));
};
although how is this related to jQuery, I don't know
虽然这与 jQuery 有什么关系,但我不知道
回答by Alain Mazy
Sorry for the digging up, but:
很抱歉挖掘,但是:
var bar = "16px";
var foo = parseInt(bar, 10); // Doesn't work! Output is always 16px
// and
var foo = Number(s.replace(/px$/, '')); // No more!
回答by Elliot Suls
$(document).ready(function(){<br>
$("#btnW1").click(function(){<br>
$("#d1").animate({<br>
width: "+=" + x,
});
});
When trying to identify the variable x with a pixel value I by using jquery I put the += in quotes. Instead of having width: '+= x', which doesn't work because it thinks that x is a string rather than a number. Hopefully this helps.
当尝试使用 jquery 使用像素值标识变量 x 时,我将 += 放在引号中。而不是具有宽度:'+= x',这不起作用,因为它认为 x 是一个字符串而不是一个数字。希望这会有所帮助。

