最近在看html5时看到的一个有意思的拖放效果,这里是简单的一个拖放删除元素的效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>拖放操作</title>
<style>
li{ list-style:none;width:100px; height: 100px; background: red; margin-bottom:20px;}
#div1{ width:200px; height: 200px; background: red; margin:0 auto;}
</style>
<script>
window.onload = function()
{
var oUl = document.getElementsByTagName("ul")[0];
var aLi = oUl.getElementsByTagName("li");
var oDiv = document.getElementById("div1");
var i = 0;
for(var i=0; i<aLi.length; i++)
{
aLi[i].index = i;
aLi[i].ondragstart =function(ev)
{
var ev = ev || window.event;
ev.dataTransfer.setData(‘name‘,this.index);
this.style.background = "green";
};
aLi[i].ondrag =function() //开始与结束之间连续触发
{
document.title = i++;
};
aLi[i].ondragend =function()
{
this.style.background = "red";
};
}
oDiv.ondragenter = function()
{
this.style.background = "blue";
}
oDiv.ondragleave = function()
{
this.style.background = "red";
}
oDiv.ondragover = function(ev) //开始与结束之间连续触发
{
//要想触发drop事件,必须要在ondragover事件中阻止默认事件
document.title = i++;
ev.preventDefault();
}
oDiv.ondrop= function(ev)
{
//this.style.background = "yellow";
//alert(ev.dataTransfer.getData("name"));
oUl.removeChild(aLi[ev.dataTransfer.getData("name")]);
for(var i=0; i<aLi.length; i++)
{
aLi[i].index = i;
}
}
}
</script>
</head>
<body>
<ul>
<li draggable="true"></li>
<li draggable="true"></li>
<li draggable="true"></li>
<li draggable="true"></li>
</ul>
<div id="div1"></div>
</body>
</html>
上图就是一个把上面小图拖放到下面的大方框中释放鼠标就可以删除当前拖放的小图。