位置会自适应调整根据#parent的高度进行自动计算
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖动</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
#parent {
margin-top: 100px;
width: 300px;
height: 250px;
border: 1px solid #ccc;
overflow: auto;
}
#drag {
width: 10%;
height: 10%;
background-color: #007bff;
color: #fff;
text-align: center;
line-height: 50px;
cursor: move;
position: relative;
}
#switch {
border: none;
margin-top: 10px;
padding: 10px;
background-color: #007bff;
color: #fff;
text-align: center;
}
.box {
margin-left: 30%;
}
</style>
<body>
<div id="parent" class="box">
<div id="drag"></div>
</div>
<div class="box">
<button id="switch">切换位置</button>
<p id="location">位置</p>
</div>
<script>
// 获取父元素和拖动元素
var parent = document.getElementById("parent");
var drag = document.getElementById("drag");
var switchBtn = document.getElementById("switch");
// 定义初始变量
var isDragging = false;
var dragStart = 0;
var dragOffset = 0;
var isLeft = true;
// 监听鼠标按下事件
drag.addEventListener("mousedown", function (event) {
isDragging = true;
dragStart = event.clientY;
dragOffset = drag.offsetTop - parent.getBoundingClientRect().top;
});
// 监听鼠标移动事件
document.addEventListener("mousemove", function (event) {
let parentHeight = parent.clientHeight;
if (isDragging) {
let dragPos = event.clientY - dragStart + dragOffset;
if (dragPos < 0) {
dragPos = 0;
}
if (dragPos > parent.clientHeight - drag.clientHeight) {
dragPos = parent.clientHeight - drag.clientHeight;
}
let location = document.getElementById("location");
let locationV = parseInt(dragPos / (parentHeight / 100));
location.innerText = "位置:" + locationV + "%";
drag.style.top = dragPos + "px";
parent.scrollTop = dragPos;
}
});
// 监听鼠标松开事件
document.addEventListener("mouseup", function () {
isDragging = false;
});
// 监听切换按钮点击事件
switchBtn.addEventListener("click", function () {
isLeft = !isLeft;
let switchText = isLeft ? "切换位置" : "切换位置";
switchBtn.innerText = switchText;
if (isLeft) {
drag.style.left = "0";
} else {
drag.style.left = parent.clientWidth - drag.clientWidth + "px";
}
});
</script>
</body>
</html>
效果图: