jQuery有height() en width()函数,返回高度或宽度像素为整数…

我怎么能得到一个填充或边缘值的元素像素和整数使用jQuery?

我的第一个想法是:

var padding = parseInt(jQuery("myId").css("padding-top"));

但是,如果填充以ems为例,我如何才能得到以像素为单位的值?


查看由Chris Pebble建议的JSizes插件,我意识到我自己的版本是正确的:)。jQuery总是以像素为单位返回值,因此只需将其解析为整数就是解决方案。

感谢Chris Pebble和Ian Robinson


当前回答

这个简单的函数可以做到:

$.fn.pixels = function(property) {
    return parseInt(this.css(property).slice(0,-2));
};

用法:

var padding = $('#myId').pixels('paddingTop');

其他回答

你应该能够使用CSS (http://docs.jquery.com/CSS/css#name)。你可能需要更具体一些,比如"padding-left"或"margin-top"。

例子:

CSS

a, a:link, a:hover, a:visited, a:active {color:black;margin-top:10px;text-decoration: none;}

JS

$("a").css("margin-top");

结果是10px。

如果您想获取整数值,可以执行以下操作:

parseInt($("a").css("margin-top"))

无耻地从Quickredfox领养。

jQuersy.fn.cssNum = function(){
    return parseInt(jQuery.fn.css.apply(this, arguments), 10);
};

更新

更改为parseInt(val, 10),因为它比parseFloat快。

http://jsperf.com/number-vs-plus-vs-toint-vs-tofloat/20

解析int

parseInt(canvas.css("margin-left")); 

0px返回0

你可以像使用任何CSS属性一样抓取它们:

alert($("#mybox").css("padding-right"));
alert($("#mybox").css("margin-bottom"));

你可以用css方法中的第二个属性来设置它们:

$("#mybox").css("padding-right", "20px");

编辑:如果你只需要像素值,使用parseInt(val, 10):

parseInt($("#mybox").css("padding-right", "20px"), 10);

比较外部和内部的高度/宽度,得到总的边距和填充:

var that = $("#myId");
alert(that.outerHeight(true) - that.innerHeight());