猿问

js使用foreach遍历,然后对dom进行style.marginLeft操作发现没有用,

<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; // 保存当前显示的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);

})()

我这种写法就不行,为什么呢?我依然是对Dom元素操作的啊,有没有人知道原因的?求教


ITMISS
浏览 1036回答 2
2回答

长风秋雁

k&nbsp;ik&nbsp;这两个在哪里定义的。是不是属性名没改,控制台应该有报错了。你要写的是key吧
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答