自定义光标增强了文档的可读性,并将用户的注意力吸引到网页的特定部分。今天我们将学习如何使用 HTML、CSS 和 Javascript 为网页创建自定义光标。
方法:
- 隐藏默认光标。
- 定义包含所有动画的类。
- 当按下鼠标按钮或移动鼠标指针时动态添加和删除这些类。
例子:
HTML
javascript
const cursor = document
.querySelector(".custom-cursor");
// Adding the animations when the
// mouse button is clicked
window.addEventListener("mousedown", (event) => {
if (!cursor.classList.contains("click")) {
cursor.classList.add("click");
setTimeout(() => {
cursor.classList.remove("click");
}, 800);
}
});
// Getting the position of the cursor
window.addEventListener("mousemove", (event) => {
let x = event.pageX - cursor.offsetWidth / 2,
y = event.pageY - cursor.offsetHeight / 2;
cursor.style.left = `${x}px`;
cursor.style.top = `${y}px`;
});
HTML
JavaScript 代码:
javascript
const cursor = document
.querySelector(".custom-cursor");
// Adding the animations when the
// mouse button is clicked
window.addEventListener("mousedown", (event) => {
if (!cursor.classList.contains("click")) {
cursor.classList.add("click");
setTimeout(() => {
cursor.classList.remove("click");
}, 800);
}
});
// Getting the position of the cursor
window.addEventListener("mousemove", (event) => {
let x = event.pageX - cursor.offsetWidth / 2,
y = event.pageY - cursor.offsetHeight / 2;
cursor.style.left = `${x}px`;
cursor.style.top = `${y}px`;
});
完整代码:
HTML
输出:
支持的浏览器:
- 谷歌浏览器
- 边缘
- 火狐浏览器
- 歌剧
- 苹果浏览器