5

I am having an issue with jQuery that I can't seem to figure out.

If I do console.log($(window).width()/2) I get a numerical value.

If I do $('.modal_box').outerWidth() I get a numerical value.

However if I try to do console.log($(window).width()/2 - $('.modal_box').outerWidth()) I get NaN. If I do the same equation but replace the - with + it works.

The window width is always wider than the .modal_box.

Why could this be? It is very frustrating.

4

3 回答 3

0

试试看

console.log(parseFloat($(window).width()/2) - parseFloat($('.modal_box').outerWidth()));
于 2012-12-18T15:23:48.940 回答
0

在处理数学和它返回的值时,我通常更喜欢将值显式解析为整数,以便我只得到我想要的值。我也想让代码尽可能地可读,就像这样:

var w = parseInt($(window).width()/2);
var mb = parseInt($('.modal_box').outerWidth());

console.log(w - mb);

这样,这console.log()两个值也更容易理解,为什么操作没有返回数字。

干杯!

于 2012-12-18T21:04:05.120 回答
0

我已经按照您的方式进行了尝试,并且效果很好,即使是负值(当减去更大的数字时)。这是小提琴,这里是代码:

$(document).ready(function(){

    alert($('#someDiv').outerWidth());
    alert($(window).width());
    alert($('#someDiv').outerWidth() - $(window).width());
});

我相信错误存在于语法中的某个地方,或者如果没有提供元素宽度的 css 属性,则可能(很远)。

以下是附加信息:

为了将它定位在屏幕的中心,'.modal_box' 应该有 'position: absolute',是 body 元素的直接同级元素并且左设置为 ($(window).width()/2) - ($('.modal_box').outerWidth()/2)。

于 2012-12-18T15:39:07.540 回答