代码之家  ›  专栏  ›  技术社区  ›  Jorge Israel Peña

比较jQuery中的大小

  •  4
  • Jorge Israel Peña  · 技术社区  · 14 年前

    我现在正在学习jQuery,我对一些东西很好奇。

    对于返回字符串大小的函数,例如:

    $(".some-class").css("line-height"); // => "18px"
    

    有没有办法比较一下?例如,如果我想在做某事之前看看它是否至少有一个特定的尺寸?

    作为一个附带问题,出于好奇:在javascript中,保存 电话号码?那么,我该怎么做呢 18 "18" "18px" ? 如果为了好玩/练习,我想实现我上面所说的,有什么方法我应该看一下,把数字从其余部分中分离出来,还是我应该简单地使用正则表达式?

    2 回复  |  直到 4 年前
        1
  •  3
  •   Matt user129975    14 年前

    我不太确定各种形式的单位,但要得到整数形式的返回值。

    if (parseInt($(".some-class").css("line-height"), 10) < 18) {
        alert("It's less than 18px!");
    }
    

    http://www.w3schools.com/jsref/jsref_parseInt.asp

        2
  •  1
  •   Community CDub    8 年前

    别忘了如果没有明确设置行高, the height returned will be " normal " (jsFiddle) ,所以你也应该处理。。。。( 正常的

    也可以使用正则表达式进行切片 px JS will do the type conversion for you (jsFiddle) :

    var height = $(".some-class").css("line-height");
    
    if (height !== "normal") {
    
         // Remove 'px' from the end. The $ means the end of the line in a regex.
       height = height.replace(/px$/, ""); 
    
        if (height < 18) {
            alert("The height (" + height + ") is less than 18");
        } else {
            alert("The height (" + height + ") is greater or equal to 18");
        }
    } else {
        alert("The height is " + height);
    }
    

    这里是 a Stack Overflow question about line-height normal ,这是 a rant about line-height normal by Eric Meyer .