<div class="box-over">
<div class="box" id="box">
<div id="ccc" class="aaa"></div>
</div>
</div>
.box-over {
width: 60%;
height: 60vh;
overflow: auto;
}
.box {
width: 140%;
height: 150vh;
margin: 200px auto;
position: relative;
border: 2px solid red;
}
.aaa {
position: absolute;
width: 50px;
height: 50px;
background-color: rgb(245, 230, 99);
border: 10px solid rgba(136, 136, 136, .5);
border-radius: 50%;
}
.aaa:hover {
cursor: pointer;
border-width: 20px;
}
.aaa:active {
background-color: rgba(168, 218, 220, 1.00);
}
let box = document.querySelector("#box");
let ccc = document.querySelector("#ccc");
let over = document.querySelector('.box-over');
ccc.onmousedown = function (event) {
//计算大盒子内部的宽高
let overW = box.getBoundingClientRect().width;
let overH = box.getBoundingClientRect().height;
//大盒子滚动条移动的距离
let overs = {
x: over.scrollWidth - over.clientWidth,
y: over.scrollHeight - over.clientHeight,
}
// 子盒子
let w = ccc.getBoundingClientRect().width / 2;
let h = ccc.getBoundingClientRect().height / 2;
// 大盒子-小盒子
let width = box.getBoundingClientRect().width - w;
let height = box.getBoundingClientRect().height - h;
// 按下的位置距离左侧的差值
let x = (window.pageXOffset + event.clientX) - this.offsetLeft
let y = (window.pageYOffset + event.clientY) - this.offsetTop
// 移动
document.onmousemove = function (e) {
// 移动的坐标-左侧的坐标=子盒子的坐标
let x1 = e.pageX - x
let y1 = e.pageY - y;
if (-w < x1 && x1 < width) {
ccc.style.left = x1 + 'px';
}
if (-h < y1 && y1 < height) {
ccc.style.top = y1 + 'px';
}
// 移动的距离/总距离=鼠标移动的距离/总长度
// 滚动条移动的距离/滚动条移动的总距离=鼠标移动的比较/总盒子可以移动的距离
over.scrollLeft = x1 / overW * overs.x
over.scrollTop = y1 / overH * overs.y
}
// 抬起
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.