简体   繁体   中英

Jquery using css function

So im just playing around with my jquery and got stuck with quite odd problem. so i'm getting width of div like this

block_width = $(".grid_block").css("width");

Now i would like to do something with that width let's say

container_width = block_width * 21;

and now if would alert container_width i would get Nah insted of numbers, what am i doing wrong?

You're getting NaN instead of numbers because the width value you receive will be a string including units

IE:

"500px"
"3em"
"27.2%"

You could parse the number with parseInt

width = ...css('width');
width = parseInt(width);

But this is completely unnecessary because jQuery has the width method .

width = ...width(); //numeric value

.css("width") returns a string representing the width, with "px" appended, ie "___px" . Multiplying that string with some number fails ( "12px" * 2 evaluates to NaN ).

You could look into the functions .width() to get the width, and .width(x) to set the width (both as numbers).

Same thing I have done with width()

var block_width = $(".grid_block").width();
var container_width = block_width * 21;
alert(container_width)

Try this Fiddle

You're assigning a string as a part of a math operation...

Try this:

block_width = parseInt($(".grid_block").css("width"));

Your css("width") returns a string, not a number. Convert it using parseInt/parseFloat or use jquery .width() function (which returns number).

Remove the px from the end and do a parseInt before your multiplication

block_width = block_width.replace("px", "")
container_width = parseInt(block_width) * 21;

You need to use jquery width() method.The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). Please check http://api.jquery.com/width/ No need to do parsing for getting the width as other posts suggest.

It is because block_width is of int type;

    block_width = intParse($(".grid_block").css("width").replace('px'));
    container_width = block_width * 21

or event better

block_width = $(".grid_block").width();
container_width = block_width * 21

Hy, I came over the same problem. .css("width") returns "20px" for example. What I did, which is sure a bit odd and you could probably solve this with regex but what I did was :

var newWidth = parseInt(($('something').css("width")).split("px")[0])+xx;//xx... Size you want to add
$('something').css("width",newWidth);

I mean you could to everything in one Line also without initializing a new variable but if somebody wants to read your code and is not into jquery or javascript yet, I think its better to split it up. Hope this helps you !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM