js实现div拖拽互换位置效果

可以实现div拖拽互换位置,可以是多个div,div中放上img还是挺有用的

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>
  <style type="text/css">
        #div1, #div2 {
            float: left;
            width: 100px;
            height: 35px;
            margin: 10px;
            padding: 10px;
            border: 1px solid #ccc;
            line-height:35px;
        }
    </style>
<script type="text/javascript">
    function allowDrop(ev) {
        ev.preventDefault();
    }
    var srcdiv = null;
    var temp = null;
    //当拖动时触发
    function drag(ev, divdom) {
        srcdiv = divdom;
        temp = divdom.innerHTML;
    }
    //当拖动完后触发
    function drop(ev, divdom) {
        ev.preventDefault();
        if (srcdiv !== divdom) {
            srcdiv.innerHTML = divdom.innerHTML;
            divdom.innerHTML = temp;
        }
    }
</script>
</head>
<body>
    <div id="div1" ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)" style="">
            <p>我是第一!</p>
        </div>
    <div id="div2" ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)" style="">
            <p>那我第二。</p>
        </div>
</body>
</html>

文章转自这里

posted @ 2019-06-20 15:30  smile简单爱  阅读(3791)  评论(1编辑  收藏  举报