js與h5的結合,初步學習。
阿新 • • 發佈:2018-12-30
初步學習拖放事件
首先了解一下與拖放事件有關的標籤,拖動某元素時依次觸發:
- dragstart
- drag
- dragend
其次瞭解某元素拖動到一個你想要拖動的目標上,依次發生:
- dragenter
- dragover
- dragleave或drop
瞭解元素的預設處理來自菜鳥教程
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
<meta name="Keywords" content ="">
<meta name="Description" content="">
<style type="text/css">
*{
margin:0;
padding: 0;
color: #ffffff;
}
#drag{
width: 100px;
height: 100px;
background-color: blue;
margin: 20 px auto;
}
#box{
width: 400px;
height: 400px;
border: 2px solid red;
margin: 40px auto;
}
</style>
</head>
<body>
<div id="drag" draggable="true"></div>
<div id="box"></div>
<script >
var drag = document.getElementById("drag");
var box = document.getElementById("box");
drag.ondragstart = function() {
this.style.backgroundColor = "green";
};
drag.ondrag = function() {
this.innerHTML = "我被拖走了...";
};
document.addEventListener("dragenter",function(event){
if(event.target.id == "box") {
event.target.style.backgroundColor = "brown";
event.target.innerHTML = "進入";
}
});
// 預設情況下,資料/元素不能在其他元素中被拖放。對於drop我們必須防止元素的預設處理
document.addEventListener("dragover", function(event) {
event.preventDefault();
});
document.addEventListener("drop", function(event) {
if(event.target.id == "box") {
drag.innerHTML = "我從盒子回來的...";
drag.style.backgroundColor = "rgb(255,255,0)";
}
else {
drag.innerHTML = "我從盒子外面回來的";
drag.style.backgroundColor = "rgb(255,0,255)";
}
});
document.addEventListener("dragleave",function(event){
if(event.target.id == "box") {
event.target.style.backgroundColor = "pink";
event.target.innerHTML = "出去";
}
});
</script>
</body>
</html>
一開始的樣子
拖拽後
進入盒子後
出盒子後
從盒子外面滑鼠釋放,該方塊變紫,從裡面釋放,該方塊變黃色