<!DOCTYPE html>
<html lang="zh-cn">
<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>demo5</title>
<style>
*{
margin: 0;
padding: 0;
}
#sliderPack{
width: 1600px;
height: 600px;
border:1px solid red;
position: relative;
margin: 100px auto;
}
.slider{
width: 300px;
height: 300px;
background-color: red;
border: 2px blue solid;
position: absolute;
left:0;
top:0;
user-select: none;
}
button{
width:1600px;
height: 100px;
font-size: 25px;
margin: 10px auto;
display: block;
border:8px solid white;
background-color: aqua;
outline: none;
color:white;
}
button:hover{
background-color:skyblue;
}
button:active{
border:8px solid aqua;
}
</style>
</head>
<body>
<div id="sliderPack">
</div>
<button type="button" id="button">增加</button>
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script>
<script>
$(function() {
let num =0;
let sliderPack = document.getElementById("sliderPack");
document.getElementById("button").onclick=function(){
num++;
// $(sliderPack).append("<div class='slider' id='slider"+num+"'></div>"); //jQuery 方法
sliderPack.insertAdjacentHTML("beforeend","<div class='slider' id='slider"+num+"'></div>"); //js原生方法
let slider = document.getElementById("slider"+num);
let x = 0;
let y = 0;
let left = 0;
let top = 0;
let isDown = false;
let id = num;
slider.onmousedown = function(e){
x = e.clientX;
y = e.clientY;
left = slider.offsetLeft;
top = slider.offsetTop;
isDown = true;
this.style["z-index"] = 1; //把这个滑块的图层设置成1
for(let i=0;i<num;i++){
if(i+1!==id){
document.getElementById("slider"+(i+1)).style["z-index"] = 0;
//把其他滑块的图层设置成0,这样点击的滑块就可以覆盖其它的滑块
}
}
this.style.cursor = "move";
};
slider.onmousemove = function(e){
if(!isDown){
return false;
}
let newX = e.clientX;
let newY = e.clientY;
let newleft = newX - (x-left);
let newTop = newY -(y-top);
if(newleft<0){
newleft = 0; //最小值
}
if(newleft> 1600 - this.offsetWidth ){
newleft = 1600 - this.offsetWidth; //最大值
}
if(newTop<0){
newTop = 0;
}
if(newTop> 600 - this.offsetHeight){
newTop = 600- this.offsetHeight;
}
this.style.left = newleft + "px";
this.style.top = newTop + "px";
};
slider.onmouseleave = function(){
isDown = false;
this.style.cursor = "default";
};
slider.onmouseup = function(){
isDown = false;
this.style.cursor = "default";
};
}
});
</script>
</body>
</html>
这种方法的多个Div拖动有个缺点,就是只适合慢速拖动鼠标,快速拖动鼠标的时候,如果鼠标移出滑块的话,滑块会停止拖动。
如果需要无论鼠标移动多快滑块照样可以跟上去的实现方案请看加强版:
https://blog.csdn.net/weixin_44161401/article/details/89684783
div 拖动基础: https://blog.csdn.net/weixin_44161401/article/details/89529489