Border-left-width returns NaN in jQuery

别等时光非礼了梦想. 提交于 2020-01-06 02:32:08

问题


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!



来源:https://stackoverflow.com/questions/12232056/border-left-width-returns-nan-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!