- 版本:1.0
- 基于jquery制作的可以進行拖拽的布局組件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>拖拽塊</title>
<script src="./js/jquery.js"></script>
<style>
body{
background: #ccc;
-o-user-select: none;
-moz-user-select: none; /*火狐 firefox*/
-webkit-user-select: none; /*webkit瀏覽器*/
-ms-user-select: none; /*IE10+*/
-khtml-user-select :none; /*早期的瀏覽器*/
user-select: none;
}
*{margin: 0;padding: 0;}
.list{
height: 300px;
box-shadow: 0 0 30px 1px #fff inset;
position: relative;
}
.gradItem{
width: 130px;
height: 60px;
line-height: 40px;
text-align: center;
float: left;
color: #666;
box-shadow: 0 0 10px 1px #fff inset;
box-sizing: border-box;
}
/* 定位 */
.gradFloat{
position: absolute;
/* 穿透當前塊 */
pointer-events: none;
border: 2px solid #fff;
}
.null{
border: 2px dashed cyan;
}
/* 按鈕 */
.add{
width: 60px;
height: 30px;
line-height: 30px;
font-size: 12px;
padding: 5px 10px;
text-align: center;
border: 1px solid #fff;
position: absolute;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div class="gradList"></div>
</body>
<script>
var startIndex = null// 拖拽塊位置
var endIndex = null// 終點塊位置
$('.gradList').on('mousedown', '.gradItem', function(e){
let x = e.offsetX
let y = e.offsetY
startIndex = $(this)
// 定位拖拽塊
$(this).addClass('gradFloat')
$('.gradFloat').css({
left: e.clientX-x,
top: e.clientY-y
})
// 新建一個占位的標簽
var $pos = $('<div class="gradItem null"></div>').css({
width: $(this).width()+6,
height: $(this).height()+6,
border: '2px dashed #fff'
})
// 把占位標簽放在當前點擊標簽的后面
$(this).after($pos)
// 在頁面移動
$(document).mousemove(function(e){
var e = e||window.event
// 移動拖拽塊
$('.gradFloat').css({
left: e.clientX-x,
top: e.clientY-y
})
$('.gradItem').mousemove(function(){
endIndex = $(this)
})
})
// 松開
$(document).mouseup(function(){
if(endIndex){
// 交換位置
var arr = $('.gradList').children()
var c = arr[startIndex.index()]
arr[startIndex.index()] = arr[endIndex.index()]
arr[endIndex.index()] = c
$('.gradList').html(arr)
}
$(startIndex).removeClass('gradFloat')// 取消定位樣式
$('.gradItem.null').remove()//移除占位標簽
$('.gradItem').off('mousemove')// 取消事件
$(document).off('mousemove mouseup')
startIndex = null//需要換位的下標清空
endIndex = null
})
})
// 渲染標簽
arr = [{
color: '#ccc'
},{
color: 'cyan'
},{
color: 'pink'
},{
color: '#ff4040'
},{
color: 'yellow'
},{
color: '#8ce483'
},{
color: '#f085da'
}]
arr.map((item, index)=>{
$('<div class="gradItem"></div>').css({
background: item.color
}).appendTo('.gradList')
})
</script>
</html>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。