Border-left-width returns NaN in jQuery

2019-08-05 06:01发布

问题:

I'm busy writing a small snippet of code that should allow cross-browser usage of the border-box box model. So far the basic functionality works fine, but I can't get the margin to work. It should adapt to the space that's available, but console returns a NaN and I have no idea where it comes from.

Here is a fiddle.

The console.log doesn't even log anything and I don't know why. Any help is greatly appreciated.

回答1:

In many parts of your fiddle you have this pattern:

($(this).css("border-left-width") * 2).replace("px", "")

You're trying to erase the px after executing a multiplication which results in a syntax error. It should be either

($(this).css("border-left-width").replace("px", "") * 2)

Which works through auto type conversion or

(parseInt($(this).css("border-left-width"), 10) * 2)

Which parses the string as an integer, removing the trailing px:

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Fiddle

parseInt reference



回答2:

Because this:

  $(this).css("padding-left")

and

$(this).css("border-left-width")

returns a string containing "px", which you try to multiply with 2, resulting in NaN. You can solve this problem by parsing the resulting strings to floats before multiplying, like this:

(parseFloat($(this).css("padding-left")) * 2 )

Hope this helps!