JavaScript忽略第二和第四循环中的appendChild

时间:2015-01-08 14:49:09

标签: javascript dom appendchild

这是成功完成我想要做的事情的小提琴: 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盒,我不知道为什么。

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

1 个答案:

答案 0 :(得分:2)

appendChild()不被忽视。它被重复用在同一个元素上。

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

0h2h3h

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

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

  

HTML DOM中的HTMLCollection是实时的;当基础文档发生变化时,它会自动更新。

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/