console
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>【经典】原生JS实现“用鼠标拖拽(drag)内容DIV”,滚动条对应同步滚动</title>
<style>
::-webkit-scrollbar {
width: 8px;
height: 8px;
background: #00000011;
}
::-webkit-scrollbar-thumb {
border-radius: 8px;
background: #00000033;
}
::-webkit-scrollbar-thumb:hover {
background: #00000055;
}
::-webkit-scrollbar-corner {
background: none;
}
.scrollContainer {
width: 900px;
height: 400px;
overflow: auto;
}
.dragContainer {
width: 1200px;
height: 600px;
display: flex;
justify-content: center;
align-items: center;
}
.dragContainer p {
width: 500px;
font-size: 40px;
font-weight: bold;
padding: 50px;
border-radius: 50px;
background-color: #409EFF;
color: white;
}
.dragContainer {
cursor: grab;
}
.dragContainer:active {
cursor: grabbing;
user-select: none;
}
</style>
</head>
<body>
<div class="scrollContainer">
<div class="dragContainer">
<p id="test">这里的文字是可以拖拽的,可以左右上下拖拽,水平垂直滚动条也会对应滚动!拖拽的幅度和滚动条移动的幅度是对应等比例的!</p>
</div>
</div>
</body>
<script>
let scrollContainer = document.querySelector(".scrollContainer");
let dragContainer = document.getElementById("test");
dragContainer.onmousedown = e => {
let mouseDownScrollPosition = {
scrollLeft: scrollContainer.scrollLeft,
scrollTop: scrollContainer.scrollTop
};
let mouseDownPoint = {
x: e.clientX,
y: e.clientY
};
dragContainer.onmousemove = e => {
let dragMoveDiff = {
x: mouseDownPoint.x - e.clientX,
y: mouseDownPoint.y - e.clientY
};
scrollContainer.scrollLeft = mouseDownScrollPosition.scrollLeft + dragMoveDiff.x;
scrollContainer.scrollTop = mouseDownScrollPosition.scrollTop + dragMoveDiff.y;
};
document.onmouseup = e => {
dragContainer.onmousemove = null;
document.onmouseup = null;
};
};
</script>
</html>