我正在尝试使用背景位置和百分比值制作一个简单的可拖动背景。目前我已经成功实现了拖动功能,但是我无法找到正确的公式使图片能够以相同的速度跟随光标移动(如果有意义的话)。
以下是一个简单的示例(仅使用x轴):
如果我点击背景中的一个白色叉号并移动鼠标,那么叉号应该始终保持在光标下,直到我到达图像或容器的末端。
这可能只是一个数学问题,但由于百分比如何与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://istack.dev59.com/5yqL8.webp');
cursor: move;
border: 2px solid transparent;
}
div:active {
border-color: red;
}
<div></div>
这可能只是一个数学问题,但由于百分比如何与background-position配合使用,让我有点困惑。有什么想法吗?
cover
意味着图像的宽度等于容器的宽度或者图像的高度等于容器的高度。有了这些信息和一些简单的数学运算,你可以计算出图像的实际高度和宽度。如果你不能做到这一点,请提出一个新问题,因为你的问题已经得到了正确的回答,后续问题不应该改变答案的内容。 - MauriceNino