首页 > 代码库 > drag drop小游戏
drag drop小游戏
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style rel="stylesheet"> .goods { width: 500px; border: 1px solid red; padding: 30px; height: 150px;; } .good { float: left;; margin: 10px 20px;; width: 100px; height: 100px;; } #one { background: green; } #two { background: black; color: #ffffff; } #three { background: pink; } .destination { width: 600px;; height: 500px; border: 1px solid deepskyblue; } </style> </head> <body> 默认顺序 1 2 3 <div class="goods"> 物品容器 <div class="good" id="temp" data-type="one"> </div> <div class="good" id="" data-type="two">2</div> </div> 仓库 <div class="destination"> </div> <script type="text/javascript"> //容器类 function Container(obj) { this.goods = document.querySelectorAll(obj.goods) || []; this.rule = obj.rule || []; this.relSort = []; this.container = document.querySelector(obj.container) || document.body; this.ondrag = obj.ondrag || null; this.addEvent(this.goods); this.count = this.goods.length; this.success = obj.success || null; this.failed = obj.failed || null; } Container.prototype.compare = function (arr1, arr2) { var result = true; arr1.forEach(function (item, index) { if (item != arr2[index]) { result = false; } }) return result; } Container.prototype.addEvent = function (goods) { var me = this; Array.prototype.forEach.call(goods, function (item) { item.setAttribute(‘draggable‘, true); item.ondragstart = function (e) { if (me.ondrag) { e.dataTransfer.setData("id", e.target.id); me.ondrag.call(me, e); } } }); this.container.ondrop = function (e) { e.preventDefault(); var source = e.dataTransfer.getData("id"); e.target.appendChild(document.querySelector(‘#‘ + source)); me.relSort.push(source); if (me.relSort.length == me.count) { if (me.compare(me.rule, me.relSort)) { me.success && me.success.call(me); } else { me.failed && me.failed.call(me); } } } this.container.ondragover = function (e) { e.preventDefault(); } } var a = new Container({ goods: ‘.good‘,//需呀拖动物体的选择器 rule: [‘one‘, ‘two‘, ‘three‘], //正确的顺序 container: ‘.destination‘,// 载体选择器 ondrag: function (e) { //开始拖动事件 }, success: function () {//如果游戏成功 回调函数 alert(‘你赢了‘); }, failed: function () {//如果游戏失败 回调函数 alert(‘游戏失败‘); } }); </script> </body> </html>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。