Size Comparison in jQuery

Hey guys, I'm learning jQuery right now, and I'm interested in something.

For functions that return dimensions in rows, for example:

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

Is there any way to compare them? For example, if I want to see if it is at least a certain size, before doing something?

I really don't plan on using this, I'm just curious. I searched but found nothing. I guess the plugin would be written. Perhaps first make sure that the comparison line has the same units, and then see which one is larger, or something like that.

As a side question, out of curiosity: in javascript, which way to save only the number? So, how do I get only 18 or "18" from "18px" ? If, for fun / practice, I wanted to implement what I said above, are there any methods that I should pay attention to, divide the number from the rest, or just use regular expressions?

+4
source share
2 answers

I'm not too sure about the various forms of units, but I get the return value as an integer.

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

Remember to set the radius of parseInt: http://www.w3schools.com/jsref/jsref_parseInt.asp

+3
source

Do not forget that if the line-height is not specified explicitly, the returned height will be " normal " (jsFiddle) , so you should also handle this .... ( normal is the default value, and it should be some kind of reasonable distance)

You can also use regex for the px fragment from the end. Once you get the line into this form, 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); } 

Here's a question about stack overflow about normal line height , and here's a story about Eric Meyer's normal line height .

+1
source

All Articles