Я пытаюсь создать увеличенный визуальный ящик с возможностью перемещения изображения на Y avis сверху вниз с помощью мыши.
Моя проблема заключается в том, что мне нужно ограничить навигацию сверху и снизу визуального изображения, чтобы избежать пробелов над и под изображением во время навигации с помощью мыши до крайности.
Вот мой код:
HTML
<div class="follower-container">
<img src="https://picsum.photos/400/600?image=1083" class="follower-image" alt="" />
</div>
CSS
.follower-container {
position: relative;
height: 100vh;
max-width: 600px;
overflow: hidden;
border: 1px solid blue;
}
.follower-image {
position: absolute;
top: 50%;
left: 0; right: 0;
width: 100%;
display: block;
width: 100%;
height: auto;
transform: translateY(-50%);
}
JS
var mouse = { x:0, y:0 };
var image_position = { x:0, y:0 };
// Get mouse position
function getMouse(e){
mouse.x = e.clientX || e.pageX;
mouse.y = e.clientY || e.pageY;
}
$('.follower-container').mousemove(function(e){
getMouse(e);
});
// Move visual regarding mouse position
function moveImage(){
var distY = mouse.y - image_position.y;
image_position.y += distY/5;
$('.follower-image').css({
'top': image_position.y + "px"
});
}
setInterval(moveImage, 20);
Мой jsfiddle: https://jsfiddle.net/balix/hc2atzun/22/
Вы можете использовать комбинацию Math.min()
и Math.max()
чтобы ограничить позицию определенным диапазоном.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min
Math.max()
вернет большее из двух пройденных номеров:
Math.max(0, 100); // 100
Math.max(12, 5); // 12
Math.min()
вернет меньшее из двух пройденных номеров:
Math.min(0, 100); // 0
Math.min(12, 5); // 5
Объединив их, вы можете ограничить заданное число в пределах диапазона. Если он находится вне диапазона, он будет максимальным (или min out) на концах диапазона:
function keepInRange(n, minNum, maxNum) {
return Math.min(Math.max(minNum, n), maxNum);
}
keepInRange(-12, 0, 100); // 0
keepInRange(30, 0, 100); // 30
keepInRange(777, 0, 100); // 100
Теперь вам нужно всего лишь вычислить математику за тем, какой диапазон номеров поддерживает ваше top
значение CSS. Я очень, очень рекомендую, чтобы вы сами это делали.
Если вы действительно не можете найти решение самостоятельно, вот оно для этого случая: https://jsfiddle.net/oeynjcpL/
Анимация становится еще лучше с requestAnimationFrame;)
var mouse = { x:0, y:0 };
var image_position = { x:0, y:0 };
// Get mouse position
function getMouse(e){
mouse.x = e.clientX || e.pageX;
mouse.y = e.clientY || e.pageY;
}
$('.follower-container').mousemove(function(e){
getMouse(e);
});
// Returns number n if is inside of minNum and maxNum range
// Otherwise returns minNum or maxNum
function keepInRange(n, minNum, maxNum) {
return Math.min(Math.max(minNum, n), maxNum);
}
// Move visual regarding mouse position
function moveImage(){
var distY = mouse.y - image_position.y;
image_position.y += distY/5;
// minHeight is the containing element height minus half the height of the image
var minHeight = $('.follower-container').height() - $('.follower-image').height() / 2;
// maxHeight is half the height of the image
var maxHeight = $('.follower-image').height() / 2;
$('.follower-image').css({
'top': keepInRange(image_position.y, minHeight, maxHeight) + "px"
});
requestAnimationFrame(moveImage);
}
requestAnimationFrame(moveImage);