HTML5拖拽功能实现的拼图游戏

建站知识 2021-07-02 23:00www.168986.cn长沙网站建设

具体代码如下所示
 

<!--代码如下,最狼蚁网站SEO优化给出了我测试用的9张250250的图片切片-->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>drag拖拽</title>
    <style>
        .box{
             float: left;
        }
        img{
            width: 150px;
            height:150px;
        }
        #puzzle{
            font-size: 0;
            margin:80px auto;
            padding: 5px;
            width: 460px;
        }
    </style>
</head>
<body>
    <div id="puzzle">
        <div class="box"><img alt="1"></div>
        <div class="box"><img alt="2"></div>
        <div class="box"><img alt="3"></div>
        <div class="box"><img alt="4"></div>
        <div class="box"><img alt="5"></div>
        <div class="box"><img alt="6"></div>
        <div class="box"><img alt="7"></div>
        <div class="box"><img alt="8"></div>
        <div class="box"><img alt="9"></div>
    </div>
    <script>
        var image = document.getElementsByTagName("img");
        var box = document.getElementsByClassName("box");
        image.draggable = true;
        var source = "";
        var nowImage;
        var nowImageBox;
        var thenImage;
        for(let i=0;i<image.length;i++){
            source = "picture"+i+".jpg";
            image[i].setAttribute("src",source);
            image[i].onmousedown = function(){
                nowImage = this;
                nowImageBox = this.parentNode;
            }
            box[i].ondragover = function(event){
             event.preventDefault(); //去除ondragover事件的默认行为,该行为默认无法将数据或者元素放置到其他元素
            }
            box[i].ondrop = function(event){
                thenImage = box[i].childNodes[0];
                box[i].appendChild(nowImage);
                nowImageBox.appendChild(thenImage);
            }
        }
    </script>
</body>
</html>

 

以上所述是长沙网络推广给大家介绍的HTML5拖拽功能实现的拼图游戏,希望对大家有所帮助,如果大家有任何疑问请给我留言,长沙网络推广会及时回复大家的。在此也非常感谢大家对狼蚁SEO网站的支持!

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by