appendChild method in a simple carousel with pure JavaScript [closed]

拈花ヽ惹草 提交于 2019-12-12 10:32:26

问题


I am trying to make a simple JavaScript carousel from scratch.

JS Fiddle

CSS

#wrapper{
    position: relative;
    width: 450px;
    height: 150px;
    margin: 0 auto;
    overflow: hidden;
}
#container{
    position: absolute;
    width: 450px;
    height: 150px;
}
.child{
    width: 150px;
    height: 150px;
    padding-top: 35px;
    float: left;
    text-align: center;
    font-size: 60px;
}
#a{ background: #FF0000; }
#b{ background: #FFFF00; }
#c{ background: #00FFFF; }

HTML

<div id="wrapper">
    <div id="container">
        <div id="a" class="child">a</div>
        <div id="b" class="child">b</div>
        <div id="c" class="child">c</div>
    </div>
</div>

JS

var firstval = 0;
function Carousel(){
    firstval += 2;
    parent = document.getElementById( 'container' );
    parent.style.left = "-" + firstval + "px";
    if( !( firstval % 150 ) ){
        setTimeout(Carousel, 3000);
        firstval = 0;
        var firstChild = parent.firstChild;
        parent.removeChild( firstChild );
        parent.appendChild( firstChild );
        return;
    }
    runCarousel = setTimeout(Carousel, 20);
}
Carousel();

Till now, it cycles like this:

a b c
b c -
c a -
a b -

I think there is something wrong with the append and timing.

Question

What am I doing wrong? Should I use appendChild and removeChild method in another way?


回答1:


Change this line:

var firstChild = parent.firstChild;

… to this:

var firstChild = parent.firstElementChild;

Otherwise, you'll sometimes be grabbing the whitespace text nodes.

You don't need the following code, because appendChild will automatically move firstChild:

parent.removeChild( firstChild );

Finally, reset the container's left to 0 here:

parent.appendChild(firstChild);
parent.style.left= 0;

Otherwise, the -150px offset will cause the second child to disappear offscreen when the first is appended to the parent.

Fiddle




回答2:


I have created a carousel in the past that matches your criteria, you can find it here https://github.com/luckyape/lucky-carousel/blob/master/lucky-carousel.js

Hope that helps.



来源:https://stackoverflow.com/questions/30563747/appendchild-method-in-a-simple-carousel-with-pure-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!