欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
拖放元素
HTML5拖放功能允许用户将元素拖放到另一个位置。放置位置可能是其他应用程序。拖动元素时,鼠标指针跟随该元素的半透明表示。
 
让我们尝试以下示例以了解其基本工作原理:
 
例试试这个代码»
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Using Drag and Drop</title>
<script>
    function dragStart(e) {
        // Sets the operation allowed for a drag source
        e.dataTransfer.effectAllowed = "move";
    
        // Sets the value and type of the dragged data
        e.dataTransfer.setData("Text", e.target.getAttribute("id"));
    }
    function dragOver(e) {
        // Prevent the browser default handling of the data
        e.preventDefault();
        e.stopPropagation();
    }
    function drop(e) {
        // Cancel this event for everyone else
        e.stopPropagation();
        e.preventDefault();
    
        // Retrieve the dragged data by type
        var data = e.dataTransfer.getData("Text");
    
        // Append image to the drop box
        e.target.appendChild(document.getElementById(data));
    }
</script>
<style>
    #dropBox {
        width: 300px;
        height: 300px;
        border: 5px dashed gray;
        background: lightyellow;
        text-align: center;
        margin: 20px 0;
        color: orange;
    }
    #dropBox img {
        margin: 25px;
    }
</style>
</head>
<body>
    <h2>Drag and Drop Demo</h2>
    <p>Drag and drop the image into the drop box:</p>
    <div id="dropBox" ondragover="dragOver(event);" ondrop="drop(event);">
        <!--Dropped image will be inserted here-->
    </div>
    <img src="../images/kites.jpg" id="dragA" draggable="true" ondragstart="dragStart(event);" width="250" height="250" alt="Flying Kites">
</body>
</html>

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h61004.shtml