需要帮助查找jquery $(document).ready()在firefox中不能正常工作的bug

Need help finding a bug with jquery $(document).ready() not working properly in firefox

本文关键字:不能 常工作 bug 工作 firefox ready 查找 帮助 jquery document      更新时间:2023-09-26

我创建了一个jquery函数,用于设置元素的宽度,以便它填充父元素中兄弟元素剩余的任何额外宽度。(基本上是flexbox)

我在$(document).ready()和$(window).resize()中调用这个函数

HTML

<body>
    <div class='pageCenter'>
        <div class='fixedCol'>my fixed col</div>
        <div class='flexCol'>my flexible col</div>
        <div class='percentCol'>my percent col</div>
    </div>
</body>
CSS

.pageCenter {
    width: 400px;
    max-width: 100%;
    margin: 0px auto;
    overflow: hidden;
    background-color: gray;
}
.fixedCol, .flexCol, .percentCol {
    float: left;
}
.fixedCol {
    width: 100px;
    background-color: green;
}
.flexCol {
    background-color: blue;
}
.percentCol {
    width: 20%;
    background-color: yellow;
}
jquery

// Execute when the document has finished loading
$(document).ready(function () {
    flexColumn();
});
// Execute on window resize
$(window).resize(function () {
    flexColumn();
});
function flexColumn() {
    // with each parent of a .flexCol
    $(".flexCol").parent().each(function (index) {
        var wrapperWidth = $(this).width(); // find its width
        var numFlexCols = $(this).children(".flexCol").size(); // get the number of .flexCol elements that are direct descendants
        // get the total width of all non .flexCol elements that are direct descendants and use it to calculate the remaining space
        var sum = 0.0;
        $(this).children().not(".flexCol").each(function (index1) {
            sum += $(this)[0].getBoundingClientRect().width;
        });
        var freeSpace = wrapperWidth - Math.ceil(sum);
        // divide the remaining space evenly among all .flexCol elements that are direct descendants
        // the fractional components of this division are given to the first .flexCol element so it may end up being 1px larger than the rest
        $(this).children(".flexCol").each(function (index1) {
            if (index1 === 0) {
                $(this).css("width", Math.ceil(freeSpace / numFlexCols));
            } else {
                $(this).css("width", Math.floor(freeSpace / numFlexCols));
            }
        });
    });
}

在webkit浏览器中一切正常,但在firefox(37.0.1版本)中,只有$(window).resize()的调用正常工作。这意味着当你在firefox中加载页面时,它不会自动调整大小,直到你调整窗口的大小,然后它才会正常工作。所以我的问题是为什么我的flexColumn()函数在使用firefox时仅在$(document).ready()调用中不起作用。

下面是代码的概要:http://jsfiddle.net/metamilo/qjs2an1e/

它实际上在firefox中正常工作,但相同的代码在我的本地wamp堆栈上运行时不能正常显示。(可能是温度问题)

我试过使用$(window).onload()而不是$(document).ready(),它没有改变。控制台也没有显示错误。

我花了将近8个小时试图追踪这个问题,并在这里浏览了数百个类似的问题,但没有发现有帮助。我将非常感谢您的任何建议,如果您需要我澄清什么,请告诉我。

好了,我知道是哪里出了问题。事实证明,我的css实际上有。less扩展,所以它被less.js解析了大约16毫秒,这延迟了最初的样式,超过了firefox执行$(document).ready()的点。把它改成。css解决了这个问题

很抱歉,我在发布我的问题和代码时没有注意到,感谢您的所有建议。

总是最愚蠢的小事情让我绊倒:/