1. 程式人生 > 實用技巧 >H5 實現div拖放位置互換

H5 實現div拖放位置互換

1 給要進行拖拽的div加上draggable="true" ondrop="drop(event,this)" ondragstart="drag(event, this)" ondragover="allowDrop(event)"三個屬性

<!-- 圖表容器 -->
    <div id="echarts_container">
        <div draggable="true" ondrop="drop(event,this)" ondragstart="drag(event, this)" ondragover="allowDrop(event)">
            <div id="chart1"></div>
        </div>
        <div draggable="true" ondrop="drop(event,this)" ondragstart="drag(event, this)" ondragover="allowDrop(event)">
            <div id="chart2"></div>
        </div>
        <div draggable="true" ondrop="drop(event,this)" ondragstart="drag(event, this)" ondragover="allowDrop(event)">
            <div id="chart3"></div>
        </div>
        <div draggable="true" ondrop="drop(event,this)" ondragstart="drag(event, this)" ondragover="allowDrop(event)">
            <div id="chart4"></div>
        </div>
        <div draggable="true" ondrop="drop(event,this)" ondragstart="drag(event, this)" ondragover="allowDrop(event)">
            <div id="chart5"></div>
        </div>
    </div>

2.放下div時,交換兩個div的內容innerHTML

var srcdiv = null;
var temp = null;

//當拖動時觸發
function drag(ev, divdom) {
    srcdiv = divdom;
    temp = divdom.innerHTML;
}

function allowDrop(ev) {
    ev.preventDefault();
}
//當放下後觸發
function drop(ev, divdom) {
    ev.preventDefault();
    if (srcdiv !== divdom) {
        srcdiv.innerHTML = divdom.innerHTML;
        divdom.innerHTML = temp;
    }

    //假如div裡面時echarts圖表
    $('div').removeAttr('_echarts_instance_')
}