js和CSS3自定義滑鼠特效

listjjjclove發表於2024-11-23

線上預覽 下載

這是一款js和CSS3自定義滑鼠特效。該特效中,使用一個DIV元素來自定義滑鼠,透過CSS程式碼來構建滑鼠的形狀,並透過js程式碼來驅動滑鼠的動畫。

使用方法

HTML結構

基本的HTML結構如下。

<!--滑鼠形狀元素-->
<div id="cursorBlob"></div>
<!--頁面內容-->
<div class="wrap">
</div>
CSS樣式

為滑鼠元素新增一些基礎的CSS樣式。

#cursorBlob {
width: 50px;
height: 50px;
background: linear-gradient(120deg, #FF1744, #E040FB, #2979FF, #00E5FF, #76FF03);
background-size: 1600% 1600%;
position: absolute;
mix-blend-mode: difference;
pointer-events: none;
z-index: 1;
transition: 0.15s linear;
animation: blobRadius 5s ease infinite, blobBackground 15s ease infinite;
}
@keyframes blobRadius {
0%, 100% {
border-radius: 43% 77% 80% 40% / 40% 40% 80% 80%;
}
20% {
border-radius: 47% 73% 61% 59% / 47% 75% 45% 73%;
}
40% {
border-radius: 46% 74% 74% 46% / 74% 58% 62% 46%;
}
60% {
border-radius: 47% 73% 61% 59% / 40% 40% 80% 80%;
}
80% {
border-radius: 50% 70% 52% 68% / 51% 61% 59% 69%;
}
}
@keyframes blobBackground {
0%, 100% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
}
Javascript

最後透過下面的JS程式碼來在滑鼠移動時,將制定的滑鼠形狀元素跟隨滑鼠一起移動。

const blobCursor = (() => {
const CURSOR = document.querySelector('#cursorBlob');
const LINKS = document.querySelectorAll('.nav__link');
const setCursorPos = e => {
const { pageX: posX, pageY: posY } = e;
CURSOR.style.top = `${posY - CURSOR.offsetHeight / 2}px`;
CURSOR.style.left = `${posX - CURSOR.offsetWidth / 2}px`;
};
document.addEventListener('mousemove', setCursorPos);
const setCursorHover = () => CURSOR.style.transform = 'scale(2.5)';
const removeCursorHover = () => CURSOR.style.transform = '';
LINKS.forEach(link => link.addEventListener('mouseover', setCursorHover));
LINKS.forEach(link => link.addEventListener('mouseleave', removeCursorHover));
})();

相關文章