jQuery calculate padding-top as integer in px

后端 未结 2 1077
南方客
南方客 2021-02-08 11:46

The only solution i have found is ($(this).innerHeight() - $(this).height()) / 2

But / 2 is not right option, because user can have padding-top:0px and padd

2条回答
  •  星月不相逢
    2021-02-08 11:55

    As far as I know, getComputedSyle and cross browser equivalents are used in jQuery when requesting .css("padding-top") so they should have already been converted to pixels.

    Another way to calculate the padding is as follows

    $.fn.padding = function () {
        // clone the interesting element
        // append it to body so that CSS can take effect
        var clonedElement = this.
            clone().
            appendTo(document.body);
    
        // get its height
        var innerHeight = clonedElement.
            innerHeight();
    
        // set its padding top to 0
        clonedElement.css("padding-top","0");
    
        // get its new height
        var innerHeightWithoutTopPadding = clonedElement.
            innerHeight();
    
        // remove the clone from the body
        clonedElement.remove();
    
        // return the difference between the height with its padding and without its padding
        return innerHeight - innerHeightWithoutTopPadding;
    
    };
    
    // Test it
    
    console.log($("div").padding()); // prints 19 in Chrome 23
    console.log($("div").css("padding-top")); // prints 19.733333587646484px
    

    ​ Located at: http://jsfiddle.net/oatkiller/9t9RJ/1/

提交回复
热议问题