admin管理员组

文章数量:1129681

jQuery has height() en width() functions that returns the height or width in pixels as integer...

How can I get a padding or margin value of an element in pixels and as integer using jQuery?

My first idea was to do the following:

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

But if padding is given in ems for example, how can I get the value in pixels?


Looking into the JSizes plugin suggested by Chris Pebble i realized that my own version was the right one :). jQuery returns always value in pixels, so just parsing it to integer was the solution.

Thanks to Chris Pebble and Ian Robinson

jQuery has height() en width() functions that returns the height or width in pixels as integer...

How can I get a padding or margin value of an element in pixels and as integer using jQuery?

My first idea was to do the following:

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

But if padding is given in ems for example, how can I get the value in pixels?


Looking into the JSizes plugin suggested by Chris Pebble i realized that my own version was the right one :). jQuery returns always value in pixels, so just parsing it to integer was the solution.

Thanks to Chris Pebble and Ian Robinson

Share Improve this question edited Feb 26, 2009 at 15:10 Malik Amurlayev asked Feb 26, 2009 at 13:43 Malik AmurlayevMalik Amurlayev 2,6082 gold badges17 silver badges15 bronze badges 2
  • Can you please choose an answer from among the answers available below? – Wes Modes Commented Apr 6, 2015 at 7:35
  • 5 A note to people in this thread: always specify radix when you use parseInt. Quoting MDN: "radix An int between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10." See: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – dgellow Commented Jan 28, 2016 at 8:28
Add a comment  | 

14 Answers 14

Reset to default 240

You should be able to use CSS (http://docs.jquery.com/CSS/css#name). You may have to be more specific such as "padding-left" or "margin-top".

Example:

CSS

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

JS

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

The result is 10px.

If you want to get the integer value, you can do the following:

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

Compare outer and inner height/widths to get the total margin and padding:

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

The parseInt function has a "radix" parameter which defines the numeral system used on the conversion, so calling parseInt(jQuery('#something').css('margin-left'), 10); returns the left margin as an Integer.

This is what JSizes use.

PLEASE don't go loading another library just to do something that's already natively available!

jQuery's .css() converts %'s and em's to their pixel equivalent to begin with, and parseInt() will remove the 'px' from the end of the returned string and convert it to an integer:

http://jsfiddle.net/BXnXJ/

$(document).ready(function () {
    var $h1 = $('h1');
    console.log($h1);
    $h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
    $h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});

Here's how you can get the surrounding dimentions:

var elem = $('#myId');

var marginTopBottom  = elem.outerHeight(true) - elem.outerHeight();
var marginLeftRight  = elem.outerWidth(true)  - elem.outerWidth();

var borderTopBottom  = elem.outerHeight() - elem.innerHeight();
var borderLeftRight  = elem.outerWidth()  - elem.innerWidth();

var paddingTopBottom  = elem.innerHeight() - elem.height();
var paddingLeftRight  = elem.innerWidth()  - elem.width();

Pay attention that each variable, paddingTopBottom for example, contains the sum of the margins on the both sides of the element; i.e., paddingTopBottom == paddingTop + paddingBottom. I wonder if there is a way to get them separately. Of course, if they are equal you can divide by 2 :)

You can just grab them as with any CSS attribute:

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

You can set them with a second attribute in the css method:

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

EDIT: If you need just the pixel value, use parseInt(val, 10):

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

This simple function will do it:

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

Usage:

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

Parse int

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

returns 0 for 0px

ok just to answer the original question:

you can get the padding as a usable integer like this:

var padding = parseInt($("myId").css("padding-top").replace("ems",""));

If you have defined another measurement like px just replace "ems" with "px". parseInt interprets the stringpart as a wrong value so its important to replace it with ... nothing.

You could also extend the jquery framework yourself with something like:

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

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

Thereby adding a function on your jquery objects called margin(), which returns a collection like the offset function.

fx.

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

Don't use string.replace("px", ""));

Use parseInt or parseFloat!

I probably use github.com/bramstein/jsizes jquery plugin for paddings and margins in very comfortable way, Thanks...

Shamelessly adopted from Quickredfox.

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

update

Changed to parseInt(val, 10) since it is faster than parseFloat.

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

Not to necro but I made this which can determine pixels based on a variety of values:

$.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;
  }
});

This way, we take into account for sizing, and auto / inherit.

本文标签: javascriptPadding or margin value in pixels as integer using jQueryStack Overflow