鍍金池/ 問(wèn)答/HTML/ js使用foreach遍歷,然后對(duì)dom進(jìn)行style.marginLeft操作

js使用foreach遍歷,然后對(duì)dom進(jìn)行style.marginLeft操作發(fā)現(xiàn)沒(méi)有用,普通for循環(huán)可以,為什么呢?

<div class="parent">
    <div class="child" data-index="0" style="background-color: red;">1</div>
    <div class="child" style="background-color: rebeccapurple;">2</div>
    <div class="child" style="background-color: yellowgreen;">3</div>
</div>

js代碼如下:

(function(){
    var child_arr = document.getElementsByClassName("child");
    var len = child_arr.length;
    var parent = document.getElementsByClassName("parent")[0];
    var move_width = parent.offsetWidth;
    var index = 0; // 保存當(dāng)前顯示的div索引
    function animate() {
        var childArr = [].slice.call(child_arr);
        if (index === len) {
            index = 0;
        }
        childArr.forEach(function(item, key) {
            if (index - key >= 0) {
                child_arr[key].style.marginLeft = '-' + move_width * (index - key) + 'px';
            } else {
                child_arr[key].style.marginLeft = move_width * (key - index) + 'px';
            }
        })
        index++;
    }
    clearInterval(t);
    var t = setInterval(animate, 1000);
})()

我這種寫(xiě)法就不行,為什么呢?我依然是對(duì)Dom元素操作的啊,有沒(méi)有人知道原因的?求教

回答
編輯回答
壞脾滊

k ik 這兩個(gè)在哪里定義的。是不是屬性名沒(méi)改,控制臺(tái)應(yīng)該有報(bào)錯(cuò)了。你要寫(xiě)的是key

2017年9月29日 12:40
編輯回答
默念

好吧,我傻逼了。
我發(fā)現(xiàn)本地代碼里進(jìn)行style賦值時(shí)里面還加了分號(hào),不過(guò)這里給出的代碼沒(méi)加分號(hào),可能我測(cè)得不仔細(xì)。
本地代碼其實(shí)是:

child_arr[key].style.marginLeft = '-' + move_width * (index - key) + 'px;' // 這里是賦值,不能有分號(hào)

需要把分號(hào)刪了就可以了。。。
233333333333333333333333.

2017年3月6日 22:26