”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 CSS 创建自定义鼠标光标

使用 CSS 创建自定义鼠标光标

发布于2024-11-08
浏览:430

Written by Samson Omojola✏️

Editor’s note: This article was last updated by Njong Emy on 5 August 2024 to update content and code blocks, as well as to offer a brief comparison of CSS and JavaScript cursors to understand scenarios when you would want to use JavaScript.

Acting as the middleman between your users and your website, cursors can either limit or greatly enhance the way your users experience your site. This is why sleek, intentionally designed, custom cursors have become a significant part of UI and UX today.

Custom cursors are an opportunity to give your users direction in an engaging way and create a memorable, immersive experience for them on your website.

In this tutorial, we’ll take a look at what custom cursors are and learn how to use CSS (and JavaScript) to create custom cursors that will give your website a creative edge. To follow along with this tutorial, you should have some knowledge of HTML, CSS, and JavaScript.

Overview of cursors in CSS

We already interact with custom cursors every day. When you hover over buttons and the pointer cursor changes to a hand, or you hover over some text and the cursor changes to a text cursor, this interactivity is achieved through custom cursors.

However, there are many other creative experiences we can provide to our users with cursors. Before we dive into creating custom cursors, you should know that CSS provides you with cursors out of the box for some frequently performed tasks.

These cursors show you what can be done at the exact location you are hovering over. Examples include cursors indicating that you should click links, drag and drop elements, zoom in and out on things, and more.

All you have to do is specify the type of cursor you want using the CSS cursor property. Some of the available cursors in CSS include:


.auto            { cursor: auto; }
.default         { cursor: default; }
.none            { cursor: none; }
.context-menu    { cursor: context-menu; }
.help            { cursor: help; }
.pointer         { cursor: pointer; }
.progress        { cursor: progress; }
.wait            { cursor: wait; }
.cell            { cursor: cell; }
.crosshair       { cursor: crosshair; }
.text            { cursor: text; }
.vertical-text   { cursor: vertical-text; }
.alias           { cursor: alias; }
.copy            { cursor: copy; }
.move            { cursor: move; }
.no-drop         { cursor: no-drop; }
.not-allowed     { cursor: not-allowed; }
.all-scroll      { cursor: all-scroll; }
.col-resize      { cursor: col-resize; }
.row-resize      { cursor: row-resize; }
.n-resize        { cursor: n-resize; }
.e-resize        { cursor: e-resize; }
.s-resize        { cursor: s-resize; }
.w-resize        { cursor: w-resize; }
.ns-resize       { cursor: ns-resize; }
.ew-resize       { cursor: ew-resize; }
.ne-resize       { cursor: ne-resize; }
.nw-resize       { cursor: nw-resize; }
.se-resize       { cursor: se-resize; }
.sw-resize       { cursor: sw-resize; }
.nesw-resize     { cursor: nesw-resize; }
.nwse-resize     { cursor: nwse-resize; }


Hover over the boxes below to see the cursors in action:

See the Pen Untitled by Samson Omojola (@Caesar222) on CodePen.

Check out the complete list of CSS cursors here.

While these cursors are useful and have some basic styling, we can certainly get more creative.

How to create a custom cursor with CSS

Creating a custom cursor with CSS is a pretty straightforward process. The first step is to find the image you want to use to replace the default cursor. You can either design one yourself or get a free PNG that suits your needs from an icon library such as FontAwesome.

Next, point the CSS cursor property to the location of the image using url. Now, the cursor property knows that it's meant to use whatever image is at that URL as its cursor:


body {
      cursor: url('path-to-image.png'), auto;
}


To ensure that this cursor is used on all parts of your website, the best place to use the cursor property is in the body tag of your HTML. However, if you want, you can assign custom cursors to specific elements instead of the whole website.

You can also add a fallback value to your cursor property. When using custom CSS properties, this value ensures that if the image that serves as your custom property is missing or cannot be loaded, then your users will have another option.

In this case, auto is the fallback descriptor for your custom cursor property. Your users will see the regular cursor if the custom one is unavailable. You can also provide more than one custom cursor (multiple fallbacks) for your website. All you have to do is add their paths to the cursor property:


body {
      cursor: url('path-to-image.png'), url('path-to-image-2.svg'), url('path-to-image-3.jpeg'), auto;
}


There are three fallback cursors in the code above.

Because they draw attention to elements you want to highlight on your website, custom cursors are best used in specific scenarios, such as:

  • Indication of special interactions
  • Storytelling purposes
  • Gaming interactions
  • In hover-effects

How to change a mouse cursor to a pointer

Say you have a table and you’d like the mouse cursor to change to a pointer (i.e., the hand icon) whenever a user hovers over a row in the table. You can use the CSS cursor property to achieve this.

Here’s an example:


Name Age City
John 30 New York
Jane 25 Chicago
Bill 35 Los Angeles

In the above code, we use the tr:hover selector to apply the cursor property to all table rows when the mouse hovers over them. The cursor property is set to pointer, which changes the mouse cursor to a hand icon.

How to hide a mouse cursor with CSS

To hide the mouse cursor with CSS, you can use the cursor property and set its value to none. Here’s an example:


This will hide the mouse cursor throughout the entire webpage. If you only want to hide the mouse cursor for a specific element, you can apply the cursor property to that individual element instead of the body element.

There are several situations in which hiding the mouse cursor might be useful, such as:

  • In a game or interactive application, hiding the mouse cursor could help create a more immersive experience for the user
  • In a presentation or slideshow, hiding the mouse cursor could reduce distractions and keep the focus on the content
  • In fullscreen video or media, hiding the mouse cursor could help prevent the user from accidentally clicking on controls or other elements

Remember that hiding the mouse cursor can be confusing or disorienting for some users, depending on the use case. This strategy should be used carefully and only when necessary.

CSS vs. JavaScript cursors

In as much as custom cursors can be created with CSS, using JavaScript also has its added advantages. Before we dive into how to create custom cursors with JavaScript, let's take a look at the advantages and disadvantages of creating custom cursors with CSS, and the same for JavaScript.

There are numerous reasons why it is preferable to create cursors with CSS:

  • Simplicity: With just a line of CSS, it is possible to toggle between numerous default types of cursors
  • Browser support: CSS custom cursors are fully supported by all browsers, so you don’t need any extra configurations to operate your websites on multiple browsers

The main disadvantage of using CSS for custom cursors is that adding animation or further customizing the cursor would involve more complexity. This is where JavaScript comes in. With JavaScript, you can add more complex interactions when the user interacts with the cursor, i.e., hovering, clicking, or moving over specific elements. By listening to specific events, the cursor's movements can then be updated. Cursors can also be more easily animated with JavaScript. With only CSS, creating complex cursor transitions may prove to be more difficult.

Just as simplicity and browser support are reasons why you should use CSS, complexity and cross-browser issues are reasons why you shouldn't use JavaScript.

How to create a custom cursor with JavaScript

Creating a custom cursor with JavaScript involves manipulating DOM elements. We'll create some DOM elements, which will serve as our custom cursor, and then use JavaScript to manipulate them. Then, as we move our cursor around, those custom elements will move around as our cursor.

Rather than design an image or download an image online, we will use CSS to design a custom cursor. I want us to use something animated that draws users in. Move your cursor around the box below to see an example of what I’m describing:

See the Pen Untitled by Samson Omojola (@Caesar222) on CodePen.

As you can see, the cursor consists of two elements — one large circle and one small one. We’ll create two div elements and give them class names:


Next, we’ll create the circles with CSS. In the code below, we assign a width and height of 50px each to the big circle. To make it a circle, we give it a border radius of 50%.

The small circle will be hollow, so we give it a border and border-radius of 50%. Then, we assign it a width and height of 6px each.

We disable the default cursor by giving cursor a value of none so that we can render the custom cursor in its place.

To add animation to the big circle, we use @keyframes.

Our animation-duration is 2.0s. At the start of this duration, we set background-color to green and opacity to 0.2. Halfway through, we set the circle’s background-color to orange. At the end of the 2s duration, we set the circle’s background-color to red.

To make the animation repeat over and over again, we set animation-iteration-count to infinite:


body{
  background-color: #171717;
  cursor: none;
  height: 120vh;
}
.small{
  width: 6px;
  height: 6px;
  border: 2px solid #fff;
  border-radius: 50%;
}
.big{
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-bottom: 20rem;
  animation-name: stretch;
            animation-duration: 2.0s;
            animation-timing-function: ease-out;
            animation-direction: alternate;
            animation-iteration-count: infinite;
            animation-play-state: running;
}

@keyframes stretch {
            0% {

                opacity: 0.2;
                background-color: green;
                border-radius: 100%;
            }

            50% {
                background-color: orange;
            }

            100% {
                background-color: red;
            }
        }


Now, to make the elements move as you move your mouse, we’ll use JavaScript.

In the code below, we use an event listener to listen for whenever a user moves their mouse over our webpage. Whenever this event takes place, we use a function to get the x and y coordinates of the mouse. We then use the x and y coordinates to move our div elements around as a representative of our cursor:


const cursorSmall = document.querySelector('.small');
const cursorBig = document.querySelector('.big');

const positionElement = (e)=> {
  const mouseY = e.clientY;
  const mouseX = e.clientX;

  cursorSmall.style.transform = `translate3d(${mouseX}px, ${mouseY}px, 0)`;

  cursorBig.style.transform = `translate3d(${mouseX}px, ${mouseY}px, 0)`;

}

window.addEventListener('mousemove', positionElement)


See the complete code alongside the interactive cursor in the below CodePen:

See the Pen Untitled by Samson Omojola (@Caesar222) on CodePen.

As you can see, we used querySelector to get access to the two div elements on the DOM. Then, we added an event listener to the webpage to listen for and detect when the user moves their mouse.

When this happens, the event listener triggers a positionElement function. In this function, we mapped these coordinates to the div elements whose DOM positions we have already selected.

We move the div elements in correspondence with the x and y coordinates of the mouse using transform and translate3d. transform repositions elements in horizontal and vertical directions, while translate3d repositions elements in 3D space.

As the mouse moves, its x and y values change, transform and translate3d get updated with the help of the event listener, and the position of each div changes in correspondence.

UX and browser compatibility when creating a custom cursor

When creating a custom cursor, you should always keep the user’s best interests in mind. One way to do this is by creating a cursor that best represents or translates the essence of an element. While custom cursors give your website a unique touch, it is important to not overdo it. Overcustomizing your cursor can frustrate and confuse your users by complicating their experience on your website.

Before you decide to create a custom cursor, you should consider its functionality. For example, will a custom cursor's features work well on an old browser?

Note that some older browsers can’t support many new CSS and JavaScript features. If you design certain areas of your website around a custom cursor that uses technologies beyond your users’ browsers, they won’t be able to engage with your website.

Creating a custom cursor with accessibility in mind

As mentioned previously, custom cursors can be helpful for users with impaired mobility and other accessibility requirements. For example, people with low vision may need very large mouse pointers that are easy to track or mouse pointers with high-contrast colors that make them stand out from various backgrounds.

A mouse can also be programmed to invert the colors of any elements it hovers over. This makes it easy for users to track what they’re reading or seeing on the screen. The text cursor or caret can also be thickened so that users with low vision don’t lose track of where the cursor is on the page while typing.

Large cursors can also benefit users with motor impairment, as they are easier to move and place on elements than small cursors.

Some users may prefer to keep the default cursor for familiarity. The use of media queries such as prefers-reduced-motion can be used to toggle or disable custom cursors for users who find them distracting:


@media
(prefers-reduced-motion: reduce) {
  *{
    cursor: auto; /*reverts to the default cursor */
  }
}


Another important technique to improve accessibility is by disabling custom cursors for screen readers. These may interfere with screen readers and create confusion for the user. Adding aria-hidden = "true" to the elements that make use of the custom cursor, ensures that they are not exposed to assistive technologies like screen readers, thereby preventing confusion.

Conclusion

In this tutorial, we learned about CSS cursors available out of the box, how to create custom cursors with CSS, how to give your webpage multiple cursors, and how to use animation in CSS and JavaScript to create custom cursors. We’ve also seen the pros and cons of using CSS and JavaScript when handling custom cursors, and when to make use of cursors that are not the default.

Custom cursors can be a great way to draw your users in, keep them engaged, and direct them efficiently if implemented correctly. If you have any further thoughts or questions about creating custom cursors with CSS, let me know in the comment section.


Is your frontend hogging your users' CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.

Creating custom mouse cursors with CSS

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app, mobile app, or website. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — start monitoring for free.

版本声明 本文转载于:https://dev.to/logrocket/creating-custom-mouse-cursors-with-css-368l?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 反应虚拟 DOM
    反应虚拟 DOM
    Introduction Hi, Gleb Kotovsky is here! Today I wanna talk about Virtual DOM, specifically - React Virtual DOM So, the virtual DOM (Virtual D...
    编程 发布于2024-11-08
  • 我如何创建我的第一个开源项目。
    我如何创建我的第一个开源项目。
    这篇文章是关于我如何决定创建和共享一个简单的工具来输入剪贴板内容,从而产生了 CBPK 项目。 动机 一切都是从我尝试登录我的 AWS EC2 机器开始的。每次我想使用 Parsec 连接到 AWS EC2 时,我都必须输入整个操作系统密码,因为没有办法通过 Parsec 进行粘贴。...
    编程 发布于2024-11-08
  • 编程语言可以模仿变量运算符吗?
    编程语言可以模仿变量运算符吗?
    编程语言可以支持变量运算符吗?编程语言本身并不支持变量运算符的概念。但是,可以通过创建自定义解决方案来模拟它们的功能。自定义运算符功能:一种常见方法是定义关联运算符名称的对象或映射及其相应的功能。例如,在 JavaScript 中,您可以创建以下对象:var operators = { ' ...
    编程 发布于2024-11-08
  • 编写 Pythonic 代码:更清晰语法的提示和技巧。
    编写 Pythonic 代码:更清晰语法的提示和技巧。
    Python 是一种流行的编程语言,以其可读性和简单性而闻名。然而,即使是经验丰富的 Python 开发人员也可以通过学习新方法来编写更清晰、更高效的代码而受益。 编写 Python 代码的技巧 以下是编写 Pythonic 代码的一些技巧: 使用描述性变量名称。选择清楚表明变量代表什么的变量名称...
    编程 发布于2024-11-08
  • 您可以使用哪些方法来处理 PHP 中的嵌套数组(递归或迭代)?
    您可以使用哪些方法来处理 PHP 中的嵌套数组(递归或迭代)?
    PHP foreach 与嵌套数组:递归方法在 PHP 中使用嵌套数组可能是一个挑战。考虑一个要访问特定嵌套数组的数组,例如主数组的第二个元素。可以使用嵌套循环方法解决该问题:foreach ($tmpArray as $innerArray) { if (is_array($innerArra...
    编程 发布于2024-11-08
  • 如何高效地检查字符串中的字符串扩展?
    如何高效地检查字符串中的字符串扩展?
    在字符串中查找字符串给定一个字符串 url_string 和一个扩展名列表 extensionsToCheck,确定是否有任何扩展名出现在字符串中。一种简单的方法是遍历列表并检查每个扩展:for extension in extensionsToCheck: if extension in ...
    编程 发布于2024-11-08
  • 以下是一些标题选项,请记住问答格式并注重开发人员的实用性:

**直接切中要害:**

* **我应该使用什么 Python SOAP 客户端库
    以下是一些标题选项,请记住问答格式并注重开发人员的实用性: **直接切中要害:** * **我应该使用什么 Python SOAP 客户端库
    有哪些 Python SOAP 客户端库可用,在哪里可以找到它们的文档?在 Python 的 SOAP 客户端库领域,存在各种选项,每种选项都满足至具体要求。对于 SOAP 和 Python 的新手来说,选择合适的库的任务可能是艰巨的。以下是可用 SOAP 客户端库及其文档的综合指南。Legacy ...
    编程 发布于2024-11-08
  • 如何防止 Pandas 在保存 CSV 时添加索引列?
    如何防止 Pandas 在保存 CSV 时添加索引列?
    避免使用 Pandas 保存的 CSV 中的索引列使用 Pandas 进行修改后保存 csv 文件时,默认行为是包含索引列。为了避免这种情况,可以在使用 to_csv() 方法时将索引参数设置为 False。为了详细说明,请考虑以下命令序列:pd.read_csv('C:/Path/to/file....
    编程 发布于2024-11-08
  • 如何在没有 JavaScript 的情况下使用 POST 参数执行 PHP 重定向?
    如何在没有 JavaScript 的情况下使用 POST 参数执行 PHP 重定向?
    带 POST 参数的 PHP 重定向提出的查询涉及将用户从一个网页重定向到另一个网页,同时保留 POST 参数。原始方法涉及通过表单将 GET 参数传输到 POST 参数,该方法被认为不是最理想的,特别是对于禁用 JavaScript 的用户而言。该问题寻求一个纯基于 PHP 的解决方案,用于重定向...
    编程 发布于2024-11-08
  • 如何在 React 中访问提供者外部的上下文时处理错误
    如何在 React 中访问提供者外部的上下文时处理错误
    使用 React 的 Context API 时,处理组件尝试访问 Provider 外部上下文的情况非常重要。如果不这样做,可能会导致意想不到的结果或难以跟踪的错误。 问题 当您使用 createContext() 创建上下文时,您可以选择传递默认值。如果组件尝试访问提供程序外部的上下文,则返回此...
    编程 发布于2024-11-08
  • Filament:删除记录时删除附件
    Filament:删除记录时删除附件
    Filament 允许您向记录添加附件,但在删除记录时不会删除附件。 为了解决这个问题,我们有两种选择: 监听模型删除事件 当模型即将被删除时,它会触发删除事件。我们可以监听此事件来触发负责在模型不再存在之前删除任何附件的功能。 在模型类中,我们可以添加 booted 方法来向模型注...
    编程 发布于2024-11-08
  • 如何在信用记录检索中实现左连接?
    如何在信用记录检索中实现左连接?
    How to Perform Left Joins in Doctrine在函数 getHistory() 中,您尝试检索用户的信用历史记录。但是,连接子句中的初始语法导致了错误。要在 Doctrine 中执行左连接,可以使用以下语法:$qb ->select('a', 'u') ...
    编程 发布于2024-11-08
  • 以下是几种可能的标题:

1. How to Make CSS Transitions Work with `ngIf` in Angular 2? 
2. Why Does `ngIf` Break My CSS Transitions in Angular 2?
3. Angular 2: Combining `ngIf` and CSS Animations for Smooth Trans
    以下是几种可能的标题: 1. How to Make CSS Transitions Work with `ngIf` in Angular 2? 2. Why Does `ngIf` Break My CSS Transitions in Angular 2? 3. Angular 2: Combining `ngIf` and CSS Animations for Smooth Trans
    Angular 2 的 ngIf 和 CSS 过渡/动画如何在 Angular 2 中使用 CSS 将 div 从右侧滑入?<div class="note" [ngClass]="{'transition':show}" *ngIf="sho...
    编程 发布于2024-11-08
  • 如何使您的 React 应用程序更快:性能提示和最佳实践
    如何使您的 React 应用程序更快:性能提示和最佳实践
    啊,反应!我们喜爱的用于构建 UI 的库。它就像一剂神奇的药剂,让我们的网络应用程序感觉具有交互性和快速性——直到有一天,它却没有了。突然,你注意到事情变慢了。点击按钮就像用信鸽寄信一样。您的应用程序从闪电般的速度变成了慢吞吞的速度,用户开始给您“看”。 但是别担心!就像咖啡可以解决大部分生活问题一...
    编程 发布于2024-11-08
  • 带有 go 工作区的 Golang 微服务模块化架构
    带有 go 工作区的 Golang 微服务模块化架构
    可扩展的代码库基础设施 Golang 在后端开发、并发操作方面表现出色,是构建可扩展和高性能后端应用程序的完美套件。由于缺乏围绕 Go 工作区的微服务架构的帖子,这是通过不同服务共享模块化代码的令人难以置信的工具,我决定分享我的实现。 项目设置 mkdir dock...
    编程 发布于2024-11-08

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3