如下图,图片可在浏览器内随意拖动

拖动前拖动后

代码如下:

<div id="box">
    <img style="vertical-align: middle;" src="http://www.w3school.com.cn/i/eg_dragdrop_w3school.gif">
</div>

<script>
    var box = document.getElementById('box');
    box.ondragstart = function(e) {
        e.dataTransfer.setData('',  e.target.id); //让拖动携带数据
    }

    document.ondragover = function(e) {
        e.preventDefault(); //取消事件的默认行为
    }
    
    document.ondrop = function(e) {
        e.preventDefault(); //取消事件的默认行为
        box.style.position = 'absolute'; //relative
        box.style.left = e.clientX + 'px';
        box.style.top = e.clientY + 'px';
    }
</script>

如下图,在下列的九宫格内可随意拖动图片

图片描述

代码如下:

<style>
    td {
        width: 178px;
        height: 46px;
        border: 1px solid rgba(0, 0, 0, 0.1);
    }
    img {
        vertical-align: middle;
    }
</style>

<table>
    <tr>
        <td ondrop="drop(event)" ondragover="allowDrop(event)"></td>
        <td ondrop="drop(event)" ondragover="allowDrop(event)"></td>
        <td ondrop="drop(event)" ondragover="allowDrop(event)"></td>
    </tr>
    <tr>
        <td ondrop="drop(event)" ondragover="allowDrop(event)"></td>               
        <td ondrop="drop(event)" ondragover="allowDrop(event)">
            <img id="box" src="http://www.w3school.com.cn/i/eg_dragdrop_w3school.gif" draggable="true" ondragstart="drag(event)">
        </td>
        <td ondrop="drop(event)" ondragover="allowDrop(event)"></td>            
    </tr>
    <tr>
        <td ondrop="drop(event)" ondragover="allowDrop(event)"></td>
        <td ondrop="drop(event)" ondragover="allowDrop(event)"></td>
        <td ondrop="drop(event)" ondragover="allowDrop(event)"></td>
    </tr>
</table>

<script type="text/javascript">
    function allowDrop(e) {
        e.preventDefault();          
    }
    
    function drag(e) {
        e.dataTransfer.setData("Text", e.target.id);
    }
    
    function drop(e) {
        e.preventDefault();
        var box_id = e.dataTransfer.getData("Text");
        e.target.appendChild(document.getElementById(box_id));
    }
</script>

kuang
47 声望5 粉丝