1、鼠标点击时:
计算彼此的z-index
获得鼠标移动方法
2、鼠标松开时
去除鼠标移动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
</title>
<style media="screen" type="text/css">
#test {
height: 600px;
width: 1200px;
background-color: #4C4C4C
}
.box {
background: #DD5246;
width: 200px;
height: 200px;
position: absolute;
top: 100px;
left: 100px;
}
.toolbar {
text-align: right;
background-color: brown;
width: 100%;
height: 10%;
}
.uniqueContent {
width: 100%;
height: 90%;
color: white;
font-size: 115px;
text-align: center;
}
</style>
</head>
<body>
<div id="test">
<div class="box">
<div class="toolbar">
<button onclick="drag('close',$(this))">关闭</button>
</div>
<div class="uniqueContent">1</div>
</div>
<div class="box" style="background-color: #FECE44;left: 350px">
<div class="toolbar">
<button onclick="drag('close',$(this))">关闭</button>
</div>
<div class="uniqueContent">2</div>
</div>
<div class="box" style="background-color: #18A160;left: 600px">
<div class="toolbar">
<button onclick="drag('close',$(this))">关闭</button>
</div>
<div class="uniqueContent">3</div>
</div>
<div class="box" style="background-color: #4A8AF4;left: 850px">
<div class="toolbar">
<button onclick="drag('close',$(this))">关闭</button>
</div>
<div class="uniqueContent">4</div>
</div>
</div>
<script src="../jquery-3.2.1.min.js"></script>
<script>
//可移动元素的鼠标点击事件
let allElementsThatCanBeMoved = $(".box");
allElementsThatCanBeMoved.mousedown(function () {
drag("mousedown", $(this));
});
//可移动元素的鼠标松开事件
allElementsThatCanBeMoved.mouseup(function () {
drag("mouseup");
});
//存放移动元素的数组
let boxs = [];
//初始化上面的数组、并编排好层叠等级
function getBoxs() {
boxs = [];
$(".box").each(function () {
boxs.push($(this));
});
for (let i = 0; i < boxs.length; i++) {
boxs[i].css("z-index", i);
}
}
getBoxs();
//当前被移动的元素
let dragged;
//拖拽方法
function drag(type, dom) {
switch (type) {
case "mousedown":
for (let i = dom.css("z-index") === boxs.length - 1 ? boxs.length + 1 : 0; i < boxs.length; i++) {
if (boxs[i].children(".uniqueContent").text() === dom.children(".uniqueContent").text()) {
boxs[i].css("z-index", boxs.length - 1);
} else {
let nowZIndex = Number(boxs[i].css("z-index"));
if (nowZIndex !== 0) {
boxs[i].css("z-index", nowZIndex - 1);
}
}
}
dragged = dom;
$("body").attr("onmousemove", "drag('mousemove')");
break;
case "mouseup":
dragged = "";
$("body").attr("onmousemove", "");
break;
case "mousemove":
dragged.css({ "top": (event.pageY - 20) + "px", "left": (event.pageX - 150) + "px" });
break;
case "close":
dom.parent().parent().remove();
break;
}
}
</script>
</body>
</html>
</html>