Javascript/Jquery:数学上划分两个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4964846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:30:18  来源:igfitidea点击:

Javascript/Jquery : Mathematically Divide Two Variables

javascriptjquery

提问by Rrryyyaaannn

Here's my code:

这是我的代码:

var frameWidth = 400;
var imageWidth = $('#inner-image').css('width');
var numberOfFrames = imageWidth/frameWidth;

How do I make "numberOfFrames" display as a quotient? I.E. process "frameWidth" and "imageWidth" as numbers, rather than objects?

如何使“numberOfFrames”显示为商?IE 将“frameWidth”和“imageWidth”处理为数字而不是对象?

Let me know if I need to explain myself more clearly. Thanks!

如果我需要更清楚地解释自己,请告诉我。谢谢!

回答by user113716

.css('width')is likely returning the value with px. You can use parseInt()to get only the number.

.css('width')很可能用 返回值px。您可以使用parseInt()仅获取数字。

var frameWidth = 400;
var imageWidth = parseInt( $('#inner-image').css('width'), 10);
var numberOfFrames = imageWidth/frameWidth;

The second argument 10specifies the base that parseInt()should use.

第二个参数10指定parseInt()应该使用的基数。

You can also use the width()(docs)method to get the result without the px.

您还可以使用width()(docs)方法来获取不带px.

var frameWidth = 400;
var imageWidth = +$('#inner-image').width();
var numberOfFrames = imageWidth/frameWidth;

Here I used the unary +operator to make it a Number instead of a String.

在这里,我使用一元运算+符使其成为数字而不是字符串。