【发布时间】:2023-04-11 12:26:03
【问题描述】:
我正在尝试使用background-position 和百分比值制作一个简单的可拖动背景。
到目前为止,我设法让拖动工作,但我似乎无法找到正确的计算方法让图像以相同的速度跟随光标(如果有意义的话)。
这是一个简单的例子(仅使用x 轴):
const container = document.querySelector('div');
const containerSize = container.getBoundingClientRect();
let imagePosition = { x: 50, y: 50 };
let cursorPosBefore = { x: 0, y: 0 };
let imagePosBefore = null;
let imagePosAfter = imagePosition;
container.addEventListener('mousedown', function(event) {
cursorPosBefore = { x: event.clientX, y: event.clientY };
imagePosBefore = imagePosAfter; // Get current image position
});
container.addEventListener('mousemove', function(event) {
if (event.buttons === 0) return;
let newXPos = imagePosBefore.x + ((cursorPosBefore.x - event.clientX) * 100 / containerSize.width);
newXPos = (newXPos < 0) ? 0 : (newXPos > 100) ? 100 : newXPos; // Stop at the end of the image
imagePosAfter = { x: newXPos, y: imagePosition.y }; // Save position
container.style.backgroundPosition = `${newXPos}% ${imagePosition.y}%`;
});
div {
width: 400px;
height: 400px;
background-position: 50% 50%;
background-size: cover;
background-repeat: no-repeat;
background-image: url('https://i.stack.imgur.com/5yqL8.png');
cursor: move;
border: 2px solid transparent;
}
div:active {
border-color: red;
}
<div></div>
如果我单击背景上的一个白色十字并移动鼠标,则十字应始终保持在光标下方,直到我到达图像末端或容器末端。
这可能只是一个数学问题,但我有点困惑,因为百分比如何与background-position 一起工作。有什么想法吗?
【问题讨论】:
标签: javascript css background-position