JS操作子節點移動位置
阿新 • • 發佈:2018-12-14
HTML:
<div id="father"> <div class="son" style="color: #8C85E6">1</div> <div class="son">2</div> <div class="son">3</div> <div class="son">4</div> <div class="son">5</div> </div> <button onclick="prev()">prev</button> <button onclick="next()">next</button>
js程式碼:
function next() { var father=document.getElementById("father") var son=document.getElementsByClassName("son"); father.insertBefore(son[son.length-1],son[0]); } function prev() { var father=document.getElementById("father") var first=document.getElementsByClassName("son")[0]; father.appendChild(first) }
實現的效果為:點選next,將第一個元素追加到末尾;點選prev,將最後一個追加到最前面;