appendChild方法在一个简单的轮播中使用纯JavaScript [英] appendChild method in a simple carousel with pure JavaScript
问题描述
我正试图从头开始制作一个简单的JavaScript轮播。
I am trying to make a simple JavaScript carousel from scratch.
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.
什么我做错了吗?我应该以另一种方式使用 appendChild
和 removeChild
方法吗?
What am I doing wrong? Should I use appendChild
and removeChild
method in another way?
推荐答案
更改此行:
var firstChild = parent.firstChild;
…对此:
… to this:
var firstChild = parent.firstElementChild;
否则,你有时会抓住空白文本节点。
Otherwise, you'll sometimes be grabbing the whitespace text nodes.
您不需要以下代码,因为 appendChild
将自动移动 firstChild
:
You don't need the following code, because appendChild
will automatically move firstChild
:
parent.removeChild( firstChild );
最后,在此处将容器的左侧重置为0:
Finally, reset the container's left to 0 here:
parent.appendChild(firstChild);
parent.style.left= 0;
否则, -150px
偏移将导致当第一个孩子被附加到父母身上时,第二个孩子会在屏幕外消失。
Otherwise, the -150px
offset will cause the second child to disappear offscreen when the first is appended to the parent.
这篇关于appendChild方法在一个简单的轮播中使用纯JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!