JavaScript 在第 2 和第 4 循环中忽略 appendChild

JavaScript ignores appendChild in 2nd and 4th loop

这是成功完成我想要做的事情的 fiddle: http://jsfiddle.net/WoofurrBro/qcf4qcm6/2/

我的设置不起作用。

function align() {
    var x = document.getElementById('container').offsetWidth;
    var y = document.getElementsByClassName('box')[0].offsetWidth;
    var z = Math.floor(x / y);
    // finds # of columns

    for (var i = 0; i < z; i++) {
        document.getElementById('container').innerHTML += '<div class=col style="width:' + y + 'px;float:left;"></div>';
    };
    // creates columns

    var columns = document.getElementsByClassName('col');
    var boxes = document.getElementsByClassName('box');
    // variables for later use
    ///////////////////////////////////////////////////////////////////////////////
    for (var i = 0; i < boxes.length; i++) {
        var minIndex;
        var column = [];
        // minIndex = shortest column, column[] to sort NodeList

        for (var iii = 0; iii < columns.length; iii++) {
            column[iii] = columns[iii].clientHeight;
        };
        // converts columns[] (NodeList) to column[] (Array)

        column.sort(function (a, b) {
            return a - b;
        });
        // sorts the column[] array

        for (var ii = 0; ii < columns.length; ii++) {
            if (column[0] == columns[ii].clientHeight) {
                minIndex = ii;
                break;
            };
        };
        // picks the first item in the column[] array (shortest) and finds the index of it in columns[] NodeList

        boxes[i].style.visibility = 'visible';
        //ALSO, placing this under the appendChild string causes weird bugs (?)
        boxes[i].innerHTML += i + 'h';
        columns[minIndex].appendChild(boxes[i]); // !!!!!!!!!!!!!! SEEMS TO IGNORE THIS appendChild
        //places them and adds identification
    };
    ///////////////////////////////////////////////////////////////////////////////
};

window.onload = align;
 * {
     -webkit-touch-callout: none;
     -webkit-user-select: none;
     -khtml-user-select: none;
     -moz-user-select: none;
     -ms-user-select: none;
     user-select: none;
     cursor:default;
     margin:0px;
     padding:0px;
 }
 html {
     background-color:#20293F;
 }
 #title {
     text-align:center;
     padding-top:40px;
     font-size:60px;
     margin-bottom:10px;
 }
 #description {
     font-size:14px;
     text-align:center;
     margin:0 auto 30px auto;
     max-width:450px;
 }
 .box {
     width:250px;
     word-wrap:break-word;
     background-color:rgba(0, 0, 0, 0.30);
     margin:10px 0 10px 0;
 }
 col {
     margin:0 10px 0 10px;
 }
 #containerwrap {
     background-color:rgba(0, 0, 0, 0.30);
     min-width:800px;
     width:100%;
 }
 #container {
     overflow:hidden;
     width:800px;
     margin:0 auto;
 }
 .postTitle {
     text-align:center;
     font-size:30px;
     color:#5F70A6;
 }
 .postBody {
     padding:10px;
     font-size:12px;
     color:#5F70A6;
 }
<div id="containerwrap">
    <div id="container">
        <div class="box">
             <h2 class="postTitle">11 boots</h2>

            <div class="postBody">
                <p>11 bbooots</p>
            </div>
        </div>
        <div class="box">
             <h2 class="postTitle"></h2>

            <div class="postBody">
                <p>22 sweg</p>
            </div>
        </div>
        <div class="box">
             <h2 class="postTitle"></h2>

            <div class="postBody">
                <p><span></span><span></span><span>33 thisisadivthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimetocopythisshitsorries<span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span></span>
                </p>
            </div>
        </div>
        <div class="box">
             <h2 class="postTitle">44 ether</h2>

            <div class="postBody">
                <p>44 infinite, silk-smooth darkness covers your eyes as you float in the skies
                    <br>lightning bolts of pleasure and happiness strike you, through your senses, as each rain drop pops silently on your skin
                    <br>the windy silence cloak guards your peace as you rest in the sky, floating upwards and feeling the rain drops pop and the air flowing around you with kind love, giving you calmness and calmness again
                    <br>this sea of magic around you might not be, but does it matter, if that’s what’s on your mind. you let it stay and you float, you float away, as you let it be
                    <br>and it strikes you that you are where your mind is and your mind is here, here in this magic place, as the raindrops pop lightning on your skin, you allow it to be, might you never leave, but if you ever left, might you come back to be here once more
                    <br>just close your eyes</p>
            </div>
        </div>
    </div>
</div>

在代码运行之前,这些框以 11 22 33 44 的顺序开始,我希望脚本动态创建三列并在每一步将它们一次放置到最短的列中。

但是,只有两个框被放入列中。 22和44的框完全被忽略了,不知道为什么。

我该怎么做才能让它正常工作?

appendChild() 没有被忽略。它在同一元素上重复使用。

如果您查看 11 框的底角,您会看到:

0h2h3h

您的 i + "h" 文本被添加到同一个框 3 次,这意味着 boxes[i] 在 3 次迭代期间引用 同一个框循环。

怎么会这样?这里的问题是 boxes 不是数组。它是一个 HTMLCollection,其内容的顺序反映了当前 DOM 中元素的顺序:

An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed.

Source

这就是正在发生的事情:

您的盒子按以下顺序开始:

[original boxes] 11 22 33 44   [columns]

所以在第一次迭代中,boxes[i] 是第 11 个框,它被添加到第一列。现在顺序是:

[original boxes] 22 33 44      [columns] 11

在下一次迭代中,boxes[i] (a.k.a. boxes[1]) 是第 33 个框,它被添加到第二列,顺序为:

[original boxes] 22 44 11      [columns] 11 33

在下一次迭代 boxes[i] (= boxes[2]) 中,第 11 个框再次 ,并将其附加到第三列。现在的顺序是:

[original boxes] 22 44         [columns] 33 11

在最后一次迭代中,boxes[i] 又是第 11 个框,它被附加到第一列:

[original boxes] 22 44         [columns] 11 33

故事到此结束。


你的 jsfiddle 工作而你的 tumblr 页面不工作的原因是在你的 tumblr 页面中,目标容器是 框的起始位置之后,但在 jsfiddle 中,容器是 框之前,所以未移动的框始终保持其顺序位置。

如果容器移动到框之后,您的 jsfiddle 将执行以下操作:

http://jsfiddle.net/qcf4qcm6/3/


解决这个问题很简单。在开始使用之前,只需将 boxes 转换为数组即可:

var boxes = document.getElementsByClassName('box');
boxes = Array.prototype.slice.apply(boxes);

这样做,一切都会正常。

http://jsfiddle.net/myqakknr/2/