实现html5拖放功能只需那么两步:
1,在需要拖放的元素上加上 draggable="true" οndragstart="drag(event)" 意思是该元素可拖动,ondragstart函数是用来设置元素放置的内容的,也可以用其它办法绑定
2,在要放置的元素上加上οndrοp="drop(event)" οndragοver="allowDrop(event)" 也可以换成别的绑定方式
下面是个使用拖放的简单计算器
<!DOCTYPE HTML>
<html>
<head>
<script src="jquery-1.9.1.js"></script>
<meta charset="utf-8">
<meta charset="utf-8">
<style>
p{
display: table;
border: 1px solid;
width: 482px;
height: 100px;
}
div{
border: 1px solid;
width: 482px;
height: 60px;
}
input{
margin-top: 10px;
width:40px;
height: 40px;
}
span{
/*font-size: 30px;*/
/*line-height: 100px;*/
text-align: center;
display: table-cell;
border: 1px solid;
width: 100px;
height: 98px;
word-wrap: break-word;
vertical-align: middle;
}
</style>
</head>
<body>
<p><span class="number">请拖动数字放在这里</span><span>+</span><span class="number">还有这里</span><span>=</span><span id="result">结果</span></p>
<div>
<input type="button" value="1" draggable="true">
<input type="button" value="2" draggable="true">
<input type="button" value="3" draggable="true">
<input type="button" value="4" draggable="true">
<input type="button" value="5" draggable="true">
<input type="button" value="6" draggable="true">
<input type="button" value="7" draggable="true">
<input type="button" value="8" draggable="true">
<input type="button" value="9" draggable="true">
<button id="reset">重置</button>
</div>
<script>
$("input").on("dragstart",function(evt){
event.dataTransfer.setData("inputV",$(this).val());
})
$(".number").on("dragover",function(evt){
event.preventDefault();
})
$(".number").on("drop",function(){
var data = event.dataTransfer.getData("inputV"),
$result = $("#result");
$(this).text(data);
var num1 = $(".number:eq(0)").text(),
num2 = $(".number:eq(1)").text();
if(!isNaN(num1) && !isNaN(num2)) {
$result.text(parseInt(num1) + parseInt(num2));
}else{
$result.text("未知结果!")
}
})
$("#reset").on("click",function(){
window.location.reload();
})
</script>
</body>
</html>