Padding or margin value in pixels as integer using jQuery

后端 未结 14 2122
陌清茗
陌清茗 2020-11-28 02:40

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 p

相关标签:
14条回答
  • 2020-11-28 03:08

    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);
    
    0 讨论(0)
  • 2020-11-28 03:12

    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.

    0 讨论(0)
  • 2020-11-28 03:15

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

    var that = $("#myId");
    alert(that.outerHeight(true) - that.innerHeight());
    
    0 讨论(0)
  • 2020-11-28 03:16

    Parse int

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

    returns 0 for 0px

    0 讨论(0)
  • 2020-11-28 03:16

    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
    
    0 讨论(0)
  • 2020-11-28 03:17

    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"))
    
    0 讨论(0)
提交回复
热议问题