Я создал собственный курсор, но у меня возникла проблема с его положением при прокрутке страницы. Вместо того, чтобы следовать за курсором мыши, он остается там, где он был на странице, пока вы снова не переместите мышь, а затем догоняет.
let mouseCursor = document.querySelector(".cursor");
window.addEventListener('DOMContentLoaded', cursor);
window.addEventListener('mousemove', cursor);
document.addEventListener('mouseenter', () => mouseCursor.style.display = 'block');
document.addEventListener('mouseleave', () => mouseCursor.style.display = 'none');
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent)) {
jQuery('.cursor').remove();
} else {
mouseCursor.style.display = 'block';
}
function cursor(e){
mouseCursor.style.top = "calc(" +e.pageY + "px - 1rem)";
mouseCursor.style.left = "calc(" +e.pageX + "px - 1rem)";
}
.section{
height:200vh;
}
.cursor{
display:none;
width: 20px;
height: 20px;
border: 2px solid #f2f2f2;
outline: 2px solid #000;
border-radius: 50%;
position: absolute;
transition: all 0.3s ease;
transition-property: background, transform;
transform-origin: center center;
z-index: 20000;
pointer-events: none;
}
<div class = "cursor"></div>
<div class = "section"></div>
Вам нужно работать с clientX/Y
собственностью, а не pageX/Y
.
Потому что координаты clientX/Y
относятся к верхнему левому углу видимой части страницы, а pageX/Y
— к верхнему левому углу всей страницы.
Кроме того, вместо того, чтобы делать свой круг position:absolute
, вы должны изменить его на position:fixed;
Элементы с фиксированным позиционированием фиксируются относительно области просмотра.
CSS абсолютное и фиксированное позиционирование
let mouseCursor = document.querySelector(".cursor");
window.addEventListener('DOMContentLoaded', cursor);
window.addEventListener('mousemove', cursor);
document.addEventListener('mouseenter', () => mouseCursor.style.display = 'block');
document.addEventListener('mouseleave', () => mouseCursor.style.display = 'none');
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent)) {
jQuery('.cursor').remove();
} else {
mouseCursor.style.display = 'block';
}
function cursor(e){
mouseCursor.style.top = "calc(" +e.clientY + "px - 1rem)";
mouseCursor.style.left = "calc(" +e.clientX + "px - 1rem)";
}
.section{
height:200vh;
}
.cursor{
display:none;
width: 20px;
height: 20px;
border: 2px solid #f2f2f2;
outline: 2px solid #000;
border-radius: 50%;
position: fixed;
transition: all 0.3s ease;
transition-property: background, transform;
transform-origin: center center;
z-index: 20000;
pointer-events: none;
}
<div class = "cursor"></div>
<div class = "section"></div>
Отвечает ли это на ваш вопрос? Элемент следует за движением мыши и прокруткой