Get css top value as number not as string?

后端 未结 3 1518
长情又很酷
长情又很酷 2021-01-30 02:15

In jQuery you can get the top position relative to the parent as a number, but you can not get the css top value as a number if it was set in px.
Say I have th

3条回答
  •  野的像风
    2021-01-30 02:22

    A slightly more practical/efficient plugin based on Ivan Castellanos' answer (which was based on M4N's answer). Using || 0 will convert Nan to 0 without the testing step.

    I've also provided float and int variations to suit the intended use:

    jQuery.fn.cssInt = function (prop) {
        return parseInt(this.css(prop), 10) || 0;
    };
    
    jQuery.fn.cssFloat = function (prop) {
        return parseFloat(this.css(prop)) || 0;
    };
    

    Usage:

    $('#elem').cssInt('top');    // e.g. returns 123 as an int
    $('#elem').cssFloat('top');  // e.g. Returns 123.45 as a float
    

    Test fiddle on http://jsfiddle.net/TrueBlueAussie/E5LTu/

提交回复
热议问题