代码之家  ›  专栏  ›  技术社区  ›  Pim Jager

是否将css最大值作为数字而不是字符串?

  •  109
  • Pim Jager  · 技术社区  · 16 年前

    在jQuery中,您可以将相对于父对象的顶部位置作为一个数字获取,但如果在中设置了css顶部值,则无法将其作为一个数字获取 px
    假设我有以下几点:

    #elem{
      position:relative;
      top:10px;
     }
    
    <div>
      Bla text bla this takes op vertical space....
      <div id='elem'>bla</div>
    </div>
    
    $('#elem').position().top; //Returns the number (10+(the vertical space took by the text))
    $('#elem').css('top'); //Returns the string '10px'
    

    但是我想用css top属性作为数字 10 .

    3 回复  |  直到 9 年前
        1
  •  220
  •   M4N    16 年前

    可以使用parseInt()函数将字符串转换为数字,例如:

    parseInt($('#elem').css('top'));
    

    更新: (正如本所建议的):你也应该给出基数:

    parseInt($('#elem').css('top'), 10);
    

        2
  •  25
  •   Ivan Castellanos    13 年前

    基于M4N答案的jQuery插件

    jQuery.fn.cssNumber = function(prop){
        var v = parseInt(this.css(prop),10);
        return isNaN(v) ? 0 : v;
    };
    

    那么你就用这个方法来得到数值

    $("#logo").cssNumber("top")
    
        3
  •  13
  •   iCollect.it Ltd    11 年前

    基于Ivan Castellanos的答案(基于M4N的答案)的更实用/高效的插件。使用 || 0

    我还提供了float和int变体,以适应预期用途:

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

    用法:

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

    http://jsfiddle.net/TrueBlueAussie/E5LTu/