<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.box1 {
width: 100px;
height: 100px;
background: salmon
}
.box2 {
width: 300px;
height: 300px;
border: 1px solid black
}
</style>
<body>
<div class="box1" draggable="true" id="source"></div>
<br>
<div class="box2" id="target"></div>
</body>
<script>
window.onload = function () {
var source = document.getElementById('source');
var target = document.getElementById('target');
source.ondragstart = function (event) {
var e = event || window.event
console.log('开始拖拽');
e.dataTransfer.setData('text', e.target.id);
}
target.ondragenter = function () {
console.log('进入目标元素')
}
target.ondragover = function (event) {
var event = event || window.event;
console.log('在目标元素中拖拽');
event.preventDefault()
}
target.ondragleave = function () {
console.log('拖放离开目标元素')
}
target.ondrop = function (event) {
console.log('拖放');
var e = event || window.event
var data = e.dataTransfer.getData('text');
e.target.appendChild(document.getElementById(data));
}
}
</script>
</html>
移动端拖拽
touchstart,touchmove,touchend
//获得拖拽的位置
e.changedTouches[0].pageY
拖拽(记录用的时候好找)
于 2022-03-23 13:51:50 首次发布