https://blog.csdn.net/weixin_44161401/article/details/89629340
上面这个是最开始的实现方案,但是有一个缺点,就是鼠标移出滑块的时候,滑块会停止移动,而这次的加强版利用全局变量的方式,克服了这个缺点,这次就算速度拉得再快,滑块照样会跟着鼠标移动。
<!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>demo6</title>
<style>
*{
margin: 0;
padding: 0;
}
#sliderPack{
width: 1600px;
border: 1px solid red;
height: 600px;
margin: 50px auto;
position: relative;
}
.slider{
width: 50px;
height:50px;
background: red;
border: 2px solid blue;
position: absolute;
left:0;
top:0;
user-select: none;
}
button{
width: 1600px;
height: 100px;
margin: auto;
border: 8px solid white;
background: aqua;
color: white;
display: block;
font-size: 30px;
outline: none;
box-sizing: content-box;
}
button:hover{
background: aquamarine;
}
button:active{
border: 8px solid aqua;
}
</style>
</head>
<body>
<div id="sliderPack">
</div>
<button type="button">增加</button>
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script>
<script>
$(function () {
let sliderPack = document.getElementById("sliderPack");
let num = 0;
let isDown = false;
let differenceX;
let differenceY;
let id;
sliderPack.onmousemove = function(e){
if(!isDown){
return false;
}
let slider = document.getElementById("slider"+id);
let newLeft = e.clientX - differenceX;
let newTop = e.clientY - differenceY;
if(newLeft < 0){
newX = 0;
}
if(newLeft > 1600 - slider.offsetWidth){
newLeft = 1600 - slider.offsetWidth;
}
if(newTop < 0){
newTop = 0;
}
if(newTop > 600 - slider.offsetHeight){
newTop = 600 - slider.offsetHeight;
}
slider.style.left = newLeft + "px";
slider.style.top = newTop + "px";
};
sliderPack.onmouseup = function(){
if(!isDown){
return false;
}
isDown = false;
document.getElementById("slider"+id).style.cursor="default";
};
sliderPack.onmouseleave = function(){
if(!isDown){
return false;
}
isDown = false;
document.getElementById("slider"+id).style.cursor="default";
};
document.getElementsByTagName("button")[0].onclick=function () {
num++;
sliderPack.insertAdjacentHTML("beforeend","<div class='slider' id='slider"+num+"'></div>");
let slider = document.getElementById("slider"+num);
let n = num;
slider.onmousedown = function (e) {
id = n;
differenceX = e.clientX - this.offsetLeft;
differenceY = e.clientY - this.offsetTop;
this.style.cursor = "move";
this.style["z-index"] = 1;
for(let i=0;i<num;i++){
if(i+1!==n){
document.getElementById("slider"+(i+1)).style["z-index"] = 0;
}
}
isDown = true;
}
};
})
</script>
</body>
</html>
Div拖动基础:https://blog.csdn.net/weixin_44161401/article/details/89529489