2017-05-26 76 views
0

我遇到了一个触发2次脚本的问题,它克隆了一些列并追加两次。无限循环克隆节点追加两次

我的目标是克隆不在视口中的元素,并将其追加到最后,然后从前面删除元素。

看起来像元素去了视口,并在条件中输入两次,我检查元素的左边是否大于其宽度。

这意味着我得到了两个相同元素的克隆,并在末尾附加了两次,这是不好的。

奇怪的是,元素的删除一次激发。

这里的一些代码:

var moving = false, 
    $holder = $('#carousel'); 

$holder.on('transitionend', function(){ 
    moving = false; // era true 
}); 

offset = 600; 

function getPosition() { 
    wrapper    = document.getElementById('carousel'); 
    wrapper_length  = wrapper.childElementCount; 
    width_of_elements  = wrapper.children[0].getBoundingClientRect().width;  
    current_left   = wrapper.children[0].getBoundingClientRect().left; 
    positive_current_left = current_left * -1;  

    if(Math.round(positive_current_left) > Math.round(width_of_elements)){ 
     // clone + set left after the last one 
     clone   = wrapper.children[0].cloneNode(true); 
     clone.style.left = wrapper.children[wrapper_length - 1].getBoundingClientRect().left + (offset * 2.6) + "px"; 

     console.log(clone); 

     // append child cloned 
     wrapper.appendChild(clone); 

     // delete element cloned 
     wrapper.removeChild(wrapper.childNodes[0]); 
    } 

    if (!moving) { 
     window.requestAnimationFrame(getPosition); 
    } 
} 

window.requestAnimationFrame(getPosition); 

我错了地方?

这里有一个小提琴看到它在行动:

fiddle

+0

如果你想要做的是一个元素移动到结束,你可以在 “重新” -appendChild。当它开始出现时,看起来有点不习惯,但你可以修复。 ;)[小提琴](https://jsfiddle.net/zc9j1x3h/4/) –

+0

Daaaaamn @ThomasWikman这很酷,更清晰的解决方案!你可以回答这个问题,我会接受:)非常感谢 – OzZie

+0

谢谢你的朋友! :D –

回答

1

如果你想要做的是一个元素移动到结束,你可以在“重新” -appendChild。当它开始出现时,看起来有点不习惯,但你可以修复。 ;)

if (Math.round(positive_current_left) > Math.round(width_of_elements)) { 
 
    // clone + set left after the last one 
 
    moveMe = wrapper.children[0]; 
 
    moveMe.style.left = wrapper.children[wrapper_length - 1].getBoundingClientRect().left + (offset * 2.6) + "px"; 
 

 
    // append child cloned 
 
    wrapper.appendChild(moveMe); 
 
}

fiddle