javascript - 为什么 Firefox 从 CSS 填充值的 parseInt 返回 NaN?

标签 javascript jquery firefox

在我正在开发的应用程序中,我们有一个带有表单内容的固定高度模态。模态内容通常比模态框长,因此用户必须在模态容器内向下滚动才能查看并填写整个表单。

每个表格<input>还有一个小工具提示出现在 <input> 下方当它处于焦点时。为了确保用户在使用 Tab 键浏览表单或单击靠近模式中当前滚动位置底部的表单字段时可以看到此工具提示,我编写了一些 JavaScript/jQuery 来在以下情况下自动滚动内容:工具提示将被模式底部隐藏。

这是我的代码:

// The amount of padding an element should always have to the bottom
var padding = 50;

// Add focus event to the form elements
$(".modal-content input, .modal-content textarea").focus(function(){

    // Get element bottom position relative to modal bottom
    var elementBottom = $(this).offset().top + $(this).height();

    var modalPadding = parseInt($('.modal-content').css('padding'), 10);

    var modalBottom = $('.modal-content').offset().top + $('.modal-content').height() + modalPadding;

    var distanceFromBottom = modalBottom - elementBottom;

    // Get current scroll location
    var modalScroll = $('.modal-content').scrollTop();

    // Scroll the modal if the element's tooltip would appear outside visible area
    if (distanceFromBottom < padding){
        var amountToScroll = padding + modalScroll + -distanceFromBottom;
        $('.modal-content').animate({ scrollTop: amountToScroll },250);
    }

});

如果脱离上下文看起来有点困惑,请不要担心;这里的问题是在第 8 行,我使用 parseInt获取内容区域 padding 的整数用于计算内容滚动量的值。

.modal-content填充值为 15px 。正如您所期望的,parseInt 返回 15然后我可以将其添加到我的 modalBottom 中的其他值中多变的。这在 ChromeSafariInternet Explorer 8 中完美运行。

但是,在 Firefox 中,这个 parseInt 总是返回 NaN (不是数字)出于某种原因。如果我替换 modalPaddingmodalBottom变量为 15 ,就像下面的代码一样,它也适用于 Firefox:

var modalBottom = $('.modal-content').offset().top + $('.modal-content').height() + 15;

显然,使用 modalPadding 的唯一原因变量是这样的,如果我们改变模态内容的填充,我们就不必更新JS代码,这是不可能的。尽管如此,Firefox 返回 NaN 还是让我很恼火。无论我如何尝试将填充值解析为整数。

首先我认为这与 parseInt 的基数值有关(以 10 为基数应该是 10),但正如你所看到的,我已经有了它,但它仍然不起作用。

我也尝试过使用parseFloat并使用 .replace('px','') 从值中删除“px”在尝试使用 parseInt 将值设置为整数之前,这两个方法都没有返回除 NaN 之外的任何内容。在火狐浏览器中。

我运行的是 Firefox 27.0.1。谁能向我解释一下为什么 Firefox 无法解析我的填充?

最佳答案

Documentation说:

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

因此您需要指定 paddingLeftpaddingTop...等

正如 live example 中所示, $.css 在 Firefox 中不会返回任何内容。

如果您的所有方向(左、右、上、下)的内边距均为 15 像素,则只需选择一个:

var modalPadding = parseInt($('.modal-content').css('paddingLeft'), 10);

关于javascript - 为什么 Firefox 从 CSS 填充值的 parseInt 返回 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22070872/

相关文章:

c++ - 如何使用 C++ 和 WinAPI 检查 Web 浏览器是否正在运行?

Firefox:编辑 HTML 并实时查看更改

php - Eclipse:如何将 *.js.php 文件突出显示为 JavaScript

javascript - 该功能在 chrome 中运行良好,但在 IE 和 Firefox 中运行不佳

javascript - 如何将 onchange 上的值传递给 jquery 中的另一个 onchange 事件

javascript - 如何在 jQuery 中调试预期的 DOM 行为?

html - padding-bottom 在 Firefox 上不显示

javascript - 如何阻止浏览器后退按钮访问 php 页面?

javascript - 如何使 javascript 函数持续触发

javascript - 扩展 jQuery UI 组件(覆盖 jQuery Datepicker 以防止错误输入)