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

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

我的第一个想法是:

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

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


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

感谢Chris Pebble和Ian Robinson


当前回答

我可能使用github.com/bramstein/jsizes jquery插件填充和边缘在非常舒适的方式,谢谢…

其他回答

你也可以自己扩展jquery框架,比如:

jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();

return {
    top: marginTop,
    left: marginLeft
}};

因此,在jquery对象上添加一个名为margin()的函数,该函数返回一个类似offset函数的集合。

fx.

$("#myObject").margin().top

不是死灵,但我做了这个,可以确定基于各种值的像素:

$.fn.extend({
  pixels: function (property, base) {
    var value = $(this).css(property);
    var original = value;
    var outer = property.indexOf('left') != -1 || property.indexOf('right') != -1 
      ? $(this).parent().outerWidth()
      : $(this).parent().outerHeight();

    // EM Conversion Factor
    base = base || 16;

    if (value == 'auto' || value == 'inherit') 
        return outer || 0;

    value = value.replace('rem', '');
    value = value.replace('em', '');

    if (value !== original) {
       value = parseFloat(value);
       return value ? base * value : 0;
    }

    value = value.replace('pt', '');

    if (value !== original) {
       value = parseFloat(value);
       return value ? value * 1.333333 : 0; // 1pt = 1.333px
    }

    value = value.replace('%', '');

    if (value !== original) {
      value = parseFloat(value);
      return value ? (outer * value / 100) : 0;
    }

    value = value.replace('px', '');
    return parseFloat(value) || 0;
  }
});

这样,我们会考虑到大小和自动/继承。

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

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

不要使用字符串。替换(“px”、" "));

使用parseInt或parseFloat!

parseInt函数有一个“radix”参数,它定义了转换中使用的数字系统,因此调用parseInt(jQuery('#something').css('margin-left'), 10);返回左边距为一个整数。

这就是JSizes所使用的。