本文实例为大家分享了jquery实现拖拽添加元素的具体代码,供大家参考,具体内容如下
需求
1.页面上有两个不同的容器,拖拽a容器的元素添加到b容器中;
2.a保持原位不dogn动,b增加新的元素,要实现的效果如下:
3.点击b容器中的元素移除元素
首先准备两个容器
页面效果如下
我是a元素
我是a元素
我是a元素
我是a元素
在css中定义好样式,区分两个容器
.bigBox {
display: flex;
width: 100%;
height: 400px;
}
#aBox {
width: 40%;
height: 100%;
background-color: pink;
}
#aBox > p {
line-height: 30px;
padding: 4px;
background-color: yellow;
}
#bBox {
width: 40%;
height: 100%;
background-color: #00BCF4;
}
.span {
border: 1px slid #ccc;
border-radius: 12px;
display: inline-block;
padding: 3px;
background-color: red;
}
封装一个添加元素的方法
function add(addId, htmlId) {
var listItem = { // 接收绑定的属性值,并赋值给数组的某一项
name: addId
}
var obj = {};
var html = ''
coloList.push(listItem)
coloList = coloList.reduce(function(item, next) { // 对数组进行去重处理
obj[next.name] ? '' : obj[next.name] = true && item.push(next);
return item;
}, []);
for (var i = 0; i < coloList.length; i++) { // 对去重后的数组渲染到页面
html += '' + coloList[i].name + ''
}
htmlId.html(html) // b容器要展示的数据
}
以下是拖拽的方法函数
var coloList = []
$(document).on('dragstart', '.drag', function(e) { // 拖拽事件绑定到元素上
var dudataId = $(this).attr("data-id") // 获取到元素绑定的属性值
$(document).on('dragenter', '#bBox', function() {
})
$(document).on('dragover', '#bBox', function() { // 这行代码一定要有,阻止事件的默认行为,才能触发鼠标放下的事件
event.preventDefault()
})
$('#bBox').on('drop', function(e) { // // 鼠标放下事件被触发把元素添加到bbox中
add(dudataId, $('#bBox'))
})
$(document).on('drop', '#bBox', function() { // 定时器解绑事件,不然会一直绑定事件,重复添加数据
var timer = setInterval(function() {
$('#bBox').off('dragover')
$('#bBox').off('dragenter')
$('#bBox').off('drop')
clearInterval(timer);
}, 30)
})
})
移除bbox的事件的方法
function remove(removeId, htmlId) {
console.log(removeId, htmlId)
var index = -1
var html = ''
// var list = coloList
for (var k = 0; k < coloList.length; k++) {
if (removeId === coloList[k].name) {
index = k
break
} else {
index = -1
}
}
if (index != -1) {
coloList.splice(index, 1)
// coloList = list
for (var i = 0; i < coloList.length; i++) { // 对去重后的数组渲染到页面
html += '' + coloList[i].name + ''
}
htmlId.html(html)
} else {
alert('暂无可移除的维度')
}
}
绑定点击事件
$('#bBox').on('click', '.span', function(e) {
remove($(this).attr("data-id"), $('#bBox')) // 参数:动态添加的属性值当前点击的元素,度量列表,维度html
})
这样就完成了呀。
以下是完整的代码:
.bigBox { display: flex; width: 100%; height: 400px; } #aBox { width: 40%; height: 100%; background-color: pink; } #aBox > p { line-height: 30px; padding: 4px; background-color: yellow; } #bBox { width: 40%; height: 100%; background-color: #00BCF4; } .span { border: 1px slid #ccc; border-radius: 12px; display: inline-block; padding: 3px; background-color: red; } 我是a元素
我是a元素
我是a元素
我是a元素
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



