Сбрасывать положение курсора/ползунка после каждого перехода изображения в галерее слайдеров до и после.Html

Программисты Html
Ответить
Anonymous
 Сбрасывать положение курсора/ползунка после каждого перехода изображения в галерее слайдеров до и после.

Сообщение Anonymous »

В галерее ползунок расположен в крайнем правом углу и настроен так, чтобы следовать за курсором, после того, как изображение перемещается при перемещении мыши влево, ползунок сбрасывается в крайнее правое положение после каждого перехода изображения, но проблема курсор не делает этого, поэтому при его перемещении ползунок переходит в то положение, в котором находится курсор, частично или полностью открывая изображение после
Я создал код для блокировки указателя в качестве доказательства концепции это работало даже при переходе через нажимает на Chrome, при нажатии на сайт активируется блокировка указателя, и красный шарик становится настраиваемым курсором, а при нажатии меняется цвет фона и положение курсора сбрасывается в крайнее правое положение, переход цвета фона может быть переходом изображения, а ползунок может следовать за собственный курсор, в идеале было бы неплохо более простое решение, не требующее блокировки указателя, но если нет, то помощь в интеграции решения для блокировки указателя с кодом галереи будет оценена по достоинству.
Слайдер, переключитесь в режим слайдера, нажав W.

Код: Выделить всё





Gallery Slider

body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #f4f4f4;
overflow: hidden;
}
.gallery {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.slide {
position: absolute;
top: 0;
left: 100%;
width: 100%;
height: 100%;
background: red;
transition: transform 0.5s ease-in-out;
}
.slide.active {
left: 0;
transform: translateX(0);
}
.after-image {
position: absolute;
top: 0;
left: 0;
height: 100%;
background: blue;
width: 0;
pointer-events: none;
}
.slider {
position: absolute;
top: 0;
left: 100%;
width: 5px;
height: 100%;
background: #fff;
cursor: pointer;
}




















const gallery = document.getElementById('gallery');
const slides = document.querySelectorAll('.slide');
let currentSlide = 0;

function resetSlider() {
const activeSlide = slides[currentSlide];
const afterImage = activeSlide.querySelector('.after-image');
const slider = activeSlide.querySelector('.slider');

afterImage.style.width = '0';
slider.style.left = '100%';
}

function showNextSlide() {
slides[currentSlide].classList.remove('active');
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].classList.add('active');
resetSlider();
}

gallery.addEventListener('mousemove', (e) =>  {
const activeSlide = slides[currentSlide];
const rect = gallery.getBoundingClientRect();
const xPos = e.clientX - rect.left;
const width = rect.width;
const percentage = Math.min(Math.max(xPos / width, 0), 1);

const afterImage = activeSlide.querySelector('.after-image');
const slider = activeSlide.querySelector('.slider');

afterImage.style.width = `${percentage * 100}%`;
slider.style.left = `${percentage * 100}%`;
});

gallery.addEventListener('click', showNextSlide);
resetSlider();





Блокировщик указателя, не могу получить фрагмент для правильной работы, работает в index.html

Код: Выделить всё

var dot = document.getElementById("dot");
var x = window.innerWidth / 2; // Start at the center horizontally
var y = window.innerHeight / 2; // Start at the center vertically
var pointerLocked = false;

// Position the dot at the initial center of the screen
dot.style.left = `${x}px`;
dot.style.top = `${y}px`;

// Function to toggle the background color and reset the dot to the far right
function toggleBackgroundColor() {
if (document.body.style.backgroundColor === "pink") {
document.body.style.backgroundColor = "purple";
} else {
document.body.style.backgroundColor = "pink";
}
resetCursorToFarRight(); // Move the cursor to the far right on color change
}

// Function to reset the cursor to the far right
function resetCursorToFarRight() {
x = window.innerWidth - 20; // Set the x position to the far right
dot.style.left = `${x}px`;
}

// Lock the pointer and toggle background color on click
document.body.addEventListener("click", function() {
toggleBackgroundColor();

// If pointer is not locked, request pointer lock
if (!pointerLocked) {
document.body.requestPointerLock(); // Lock the pointer
}
});

// Listen for pointer lock change to handle the cursor state
document.addEventListener("pointerlockchange", function() {
if (document.pointerLockElement === document.body) {
pointerLocked = true; // Pointer is now locked
dot.style.visibility = "visible"; // Show the controlled dot during pointer lock
document.body.style.cursor = "none"; // Hide the system cursor
document.getElementById('message').innerText = "Move your mouse to move the dot. Press 'Q' to reset.  Press Esc to exit Pointer Lock.";
} else {
pointerLocked = false; // Pointer is unlocked
dot.style.visibility = "hidden"; // Hide the dot (custom cursor) after pointer lock is exited
document.body.style.cursor = "auto"; // Show the system cursor
document.getElementById('message').innerText = "Click anywhere to activate Pointer Lock.";
}
});

// Track mouse movement when pointer is locked
document.addEventListener("mousemove", function(event) {
if (document.pointerLockElement === document.body) {
x += event.movementX; // Move horizontally
y += event.movementY; // Move vertically, but this will be restricted later

// Restrict the cursor horizontally
if (x < 0) {
x = 0; // Restrict movement at the left edge
}
if (x > window.innerWidth - 20) {
x = window.innerWidth - 20; // Restrict movement at the right edge
}

// Keep the y position fixed (vertically locked)
y = window.innerHeight / 2;

dot.style.left = `${x}px`;
dot.style.top = `${y}px`;
}
});

// Listen for keyboard input to reset dot position to the far right (press 'Q')
document.addEventListener("keydown", function(event) {
if (document.pointerLockElement === document.body && event.key.toLowerCase() === 'q') {
resetCursorToFarRight(); // Reset the dot position to the far right
}
});

// Handle Escape key to exit pointer lock manually
document.addEventListener('keydown', function(event) {
if (event.key === 'Escape' && document.pointerLockElement === document.body) {
document.exitPointerLock();
}
});

Код: Выделить всё

body {
margin: 0;
overflow: hidden;
background-color: pink;
height: 100vh;
}

#dot {
position: absolute;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
pointer-events: none;
z-index: 999;
opacity: 0.8;
visibility: hidden;
/* Hidden before pointer lock */
}

#message {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
font-family: Arial, sans-serif;
font-size: 16px;
color: #333;
}

Код: Выделить всё


Click anywhere to activate Pointer Lock. Press 'Q' to reset the dot position.



Подробнее здесь: https://stackoverflow.com/questions/793 ... -after-sli
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Html»