拖拽图片添加到页面
<div id="drag" style="width: 50px;height: 50px; background-color:#e32;"></div>
<script>
let drag = document.querySelector('#drag');
drag.addEventListener('dragover', (e) => {
e.preventDefault();
})
drag.addEventListener('drop', (e) => {
e.preventDefault();
// e.dataTransfer.files[0]获取到拖拽对象的数据
// console.log(e.dataTransfer.files[0]);
// 创建一个fileReader对象
let reader = new FileReader();
reader.readAsDataURL(e.dataTransfer.files[0]);
reader.onload = (e) => {
// 获得上传文件的base64数据
console.log(e.target.result);
let img = new Image();
img.src = e.target.result;
document.body.appendChild(img);
}
})
</script>
通过拖拽添加节点元素
<p>Drop your favorite fruits below:</p>
<ol ondragstart="dragStartHandler(event)" ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)" ondrop="dropHandler(event)">
<li draggable="true" data-value="fruit-apple">Apples</li>
<li draggable="true" data-value="fruit-orange">Oranges</li>
<li draggable="true" data-value="fruit-pear">Pears</li>
</ol>
<script>
var internalDNDType = 'text/x-example'; // set this to something specific to your site
function dragStartHandler(event) {
console.log("dragStartHandler");
if (event.target instanceof HTMLLIElement) {
// use the element's data-value="" attribute as the value to be moving:
event.dataTransfer.setData(internalDNDType, event.target.dataset.value);
event.dataTransfer.effectAllowed = 'move'; // only allow moves
} else {
event.preventDefault(); // don't allow selection to be dragged
}
}
function dragEnterHandler(event) {
console.log("dragEnterHandler");
var items = event.dataTransfer.items;
for (var i = 0; i < items.length; ++i) {
var item = items[i];
if (item.kind == 'string' && item.type == internalDNDType) {
event.preventDefault();
return;
}
}
}
function dragOverHandler(event) {
console.log("dragOverHandler");
event.dataTransfer.dropEffect = 'move';
event.preventDefault();
}
function dropHandler(event) {
console.log("dropHandler");
var li = document.createElement('li');
var data = event.dataTransfer.getData(internalDNDType);;
console.log("dropHandler==========", data);
if (data == 'fruit-apple') {
li.textContent = 'Apples';
} else if (data == 'fruit-orange') {
li.textContent = 'Oranges';
} else if (data == 'fruit-pear') {
li.textContent = 'Pears';
} else {
li.textContent = 'Unknown Fruit';
}
event.target.appendChild(li);
}
</script>