版权声明:未经同意,不得随意转载转载 https://blog.csdn.net/lucky541788/article/details/86677059
拖拽接口
<div class="box1">
<!--在h5中,如果想拖拽元素,就必须为元素添加 draggable="true" 。图片和超链接默认就可以拖拽-->
<p class="text" draggable="true">来拖拽我啊!</p>
</div>
<div class="box2"></div>
/*拖拽事件*/
var p = document.querySelector(".text");
var aim = document.querySelector(".box2");
/*应用于被拖拽元素的事件
ondrag:整个拖拽过程都会调用——持续
ondragstart:拖拽开始时调用
ondragleave:鼠标离开拖拽元素时调用
ondragend:拖拽结束时调用*/
p.ondragstart = function () {
console.log('obj + ondragstart');
};
p.ondragend = function () {
console.log('obj + ondragend');
};
p.ondragleave = function () {
console.log('obj + ondragleave');
};
p.ondrag = function () {
// console.log('obj + ondrag');
};
/*应用于目标元素的事件
ondragenter:当拖拽元素进入时调用
ondragover:当停留在目标元素上时调用——持续
ondrop:当在目标元素上松开鼠标时调用
ondragleave:当鼠标离开目标元素时调用*/
aim.ondragenter = function () {
console.log('aim + ondragenter');
};
aim.ondragover = function (e) {
// console.log('aim + ondragover');
/*如果想触发ondrop事件,那么必须在这里阻止浏览器的默认行为*/
e.preventDefault();
};
/*浏览器默认会阻止ondrop事件:必须在ondragover中阻止浏览器的默认行为*/
aim.ondrop = function () {
console.log('aim + ondrop');
/*添加被拖拽的元素到当前目标元素*/
this.appendChild(p);
};
aim.ondragleave = function () {
console.log('aim + ondragleave');
};
拖拽优化(实现任意元素拖拽)
被拖拽元素需要定义 id
<div class="box1">
<!--在h5中,如果想拖拽元素,就必须为元素添加 draggable="true" 。图片和超链接默认就可以拖拽-->
<p class="text" id="text1" draggable="true">来拖拽我啊!1</p>
<p class="text" id="text2" draggable="true">来拖拽我啊!2</p>
</div>
<div class="box2"></div>
<div class="box3"></div>
/*拖拽事件*/
/*应用于被拖拽元素的事件*/
document.ondragstart = function (e) {
/*随意添加的拖拽样式*/
e.target.style.opacity = 0.1;
e.target.style.backgroundColor='red';
/*通过dataTransfer来实现数据的储存与获取
* setData(format,data):
* format:数据的类型:text/html text/uri-list
* data:数据:一般来说是字符串值*/
e.dataTransfer.setData('text/html', e.target.id)
};
document.ondragend = function (e) {
e.target.style.opacity = 1;
e.target.style.backgroundColor='skyblue';
};
document.ondragleave = function () {};
document.ondrag = function () {};
/*应用于目标元素的事件*/
document.ondragenter = function () {};
document.ondragover = function (e) {
e.preventDefault();
};
document.ondrop = function (e) {
/*通过e.dataTransfer.setData储存的数据,只能在drop事件中获取*/
var id = e.dataTransfer.getData('text/html');
// console.log(id);
e.target.appendChild(document.getElementById(id))
};
document.ondragleave = function () {};