По наведению на ссылку менять цвет курсора
Как по наведению на ссылку менять цвет курсора? По одной ссылке без проблем а вот когда их много, непонятно...
document.addEventListener('DOMContentLoaded', () => {
const cursor = document.getElementById('cursor');
const hover = document.querySelectorAll('.link');
document.addEventListener('mousemove', (evt) => {
cursor.style = `top: ${evt.pageY}px; left: ${evt.pageX}px`;
hover.forEach((item, i) => {
const target = evt.target;
if (item === target) {
cursor.style.background = 'red';
} else {
cursor.style.background = '';
}
});
});
});
* {
cursor: none;
}
#cursor {
height: 20px;
width: 20px;
border-radius: 20px;
background: blue;
position: absolute;
}
a {
display:block;
font-size: 24px;
margin-bottom: 20px;
}
<a class="link" href='#'>Ссылка 1</a>
<a class="link" href='#'>Ссылка 2</a>
<p>Text</p>
<div id="cursor"></div>
Ответы (1 шт):
Автор решения: InDevX
→ Ссылка
Можно просто проверять наличие класса link у evt.target
document.addEventListener('DOMContentLoaded', () => {
const cursor = document.getElementById('cursor');
document.addEventListener('mousemove', (evt) => {
cursor.style = `top: ${evt.pageY}px; left: ${evt.pageX}px`;
cursor.style.background = evt.target.classList.contains('link') ? 'red' : '';
});
});
* {
cursor: none;
}
#cursor {
height: 20px;
width: 20px;
border-radius: 20px;
background: blue;
position: absolute;
}
a {
display:block;
font-size: 24px;
margin-bottom: 20px;
}
<a class="link" href='#'>Ссылка 1</a>
<a class="link" href='#'>Ссылка 2</a>
<p>Text</p>
<div id="cursor"></div>
upd. то же самое на css (не всегда работает, в отличии от js):
.link:hover ~ #cursor {
background: red;
}