js交换两个div的位置


demo

js代码

function exchange(el1, el2){
        var ep1 = el1.parentNode,
            ep2 = el2.parentNode,
            index1 = Array.prototype.indexOf.call(ep1.children, el1),
            index2 = Array.prototype.indexOf.call(ep2.children, el2);
        ep2.insertBefore(el1,ep2.children[index2]);
        ep1.insertBefore(el2,ep1.children[index1]);
    }

  代码非常简短,开始以为需要判断被交换的element是否是父层最后一个,但是实际看来,如果insertBefore第二个参数是undefined的话,那么是直接appendChild的。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM