<!DOCTYPE HTML>
<html>
<head>
<title>数字游戏</title>
<meta charset="utf-8">
<style>
h1{
text-align:center;
}
#box{
width:600px;
height:600px;
border:1px solid chartreuse;
position:absolute;
left:calc(50% - 300px);
top:calc(50% - 300px);
text-align:center;
}
#box div{
box-sizing:border-box;
width:200px;
height:200px;
float:left;
background-color:darkcyan;
border:1px solid chartreuse;
font:bolder 18px/200px "微软雅黑";
color:#FFF;
}
</style>
<script>
//页面加载结束才触发脚步
window.onload = function () {
var list = document.getElementById('box').getElementsByTagName('div');
for(var i = 0; i < list.length; i++){
list[i].draggable = true;
list[i].ondragstart = divOnDragStart;
list[i].ondragover = divOnDragOver;
list[i].ondrop = divOnDrop;
}
}
//开始拖动
function divOnDragStart(){
event.dataTransfer.setData('srcId',event.target.id);
//console.log(event.target.id);
console.log('dragstart' + event.target.id);
}
//放下的 时候
function divOnDragOver(){
event.preventDefault();//阻止默认行为
console.log('dragstart' + event.target.id);
}
//松开,丢下去
function divOnDrop(){
//event.preventDefault();
// console.log('drop');
console.log('dragstart' + event.target.id);
var srcId = event.dataTransfer.getData('srcId');
var scrNum = document.getElementById(srcId).innerText;
document.getElementById(srcId).innerText = event.target.innerText;
event.target.innerText = scrNum;
}
</script>
</head>
<body>
<h1>文字游戏</h1>
<div id="box">
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
<div id="div5">5</div>
<div id="div6">6</div>
<div id="div7">7</div>
<div id="div8">8</div>
<div id="div9">9</div>
</div>
</body>
</html>
用jQuery写出来
相关分类