2014-05-21 23 views
1

我有一堆class="section" div,我想用它們中的向上/向下按鈕移動。向上按鈕工作正常,但向下按鈕我必須按兩次才能讓div向下移動一個點。不能讓我的頭靠近它。 Firefox和Chrome一樣。嘗試在Javascript中滾動insertAfter()的怪異行爲

我在做什麼錯?

的HTML:

<div class="section"> 
. 
. //content goes here 
. 
    <button class="up" type="button">up</button> 
    <button class="down" type="button">down</button> 
</div> 

JavaScript的

//event listeners 
var classup = document.getElementsByClassName("up"); 
var classdown = document.getElementsByClassName("down"); 
for (var i=0; i<classup.length; i++) { 
    classup[i].addEventListener('click', upf, false); 
    classdown[i].addEventListener('click', downf, false); 
} 

//functions 

function downf() { 
    var temp = this.parentNode; 
    temp.parentNode.insertBefore(temp, temp.nextSibling.nextSibling); 
} 

function upf() { 
    var temp = this.parentNode; 
    temp.parentNode.insertBefore(temp, temp.previousElementSibling); 
} 

回答

2

您已經使用.nextSibling,而不是.nextElementSibling。當點擊down時,這會將您的部分移動到以下空格文本節點之後。

function downf() { 
    var section = this.parentNode; 
    if (section.nextElementSibling) 
     section.parentNode.insertBefore(section, section.nextElementSibling.nextElementSibling); 
} 
+0

現貨上。謝謝! – user3660636