- Changing the Cursor with CSS for Better User Experience (or Fun)
- Создаем собственный курсор при помощи CSS и JavaScript
- Кастомизация курсора мыши с помощью CSS
- Как сделать собственные курсоры мыши с помощью JavaScript
- Как с помощью JavaScript заставить курсоры двигаться
- Какой метод лучше?
- How to Create a Custom Mouse Cursor with CSS or JavaScript
- 1. Adding a Custom Cursor with CSS
Changing the Cursor with CSS for Better User Experience (or Fun)
CSS can control the appearance of a cursor. There are a ton of options available to us and we’ve covered them pretty thoroughly in the ol’ Almanac here on CSS-Tricks. Still, it’s easy to overlook cursors and their impact on the user experience of our sites. Remember when we learned ::selection was a thing and every site started using it to personalize the background color of text selections? Customizing cursors is just as easy and adds that extra bit of understated flourish when used correctly. In this post I’ll cover two ways I think controlling the cursor in CSS can improve user experience.
Using the Correct Cursor on an Element
Some cursor changes are built into the User Agent Stylesheet. Look at links as an example. Even if we do nothing else in our CSS, links will have color: blue; and text-decoration: underline; . That’s a solid visual indicator that the hyperlinked text is clickable. Browsers take it a bit further. Hover over the link and the cursor changes from the default black arrow to a hand with its index finger extended, otherwise known as a pointer. There are some times where the default cursor behavior from the User Agent Stylesheet doesn’t cut it. In these cases, we ought to change the cursor to something that reflects the expected user interaction on that element. Take the jQueryUI draggable() function. We can apply that to an element and it will allow a user to click and drag that element around the viewport, but the user never know that if the cursor remains in its default state. Adding cursor: move; to the element would help solve that. See the Pen QNqMRp by Geoff Graham (@geoffgraham) on CodePen. The same is true for any number of scenarios, whether we’re talking about form inputs, images, or just about anything else you can imagine. Always take the opportunity to match an element’s cursor to its behavior when the default arrow isn’t enough of a clue. Here’s a demo of everything currently available: See the Pen The Cursors! by Chris Coyier (@chriscoyier) on CodePen.
Using a Custom Cursor to Enhance an Element
What about custom cursors, you ask? As in, an image of your own creation tha takes the place of a cursor. Of course that’s possible! We can point the cursor property to an image like this:
I find this comes in handy when adding just a touch of personalization fits, but the user might not expect it. For example, a form where the answer to a question corresponds to a specific emotion: See the Pen qZjwGe by Geoff Graham (@geoffgraham) on CodePen. I found working with emoji to be a bit of a trick in and of itself. You can copy and paste emoji from a site like this, then paste it into a text editor and save it as a PDF, which can then be opened in Illustrator. From there, I was able to select the image, paste it into Photoshop and create a PNG image with a transparent background. Boom! For those of you curious about SVG, I’m happy to say it’s a go! The cursor property does accept SVG files in all its glory. No animated GIF’s though, sadly. See the Pen QNgoQW by Geoff Graham (@geoffgraham) on CodePen. So no animated cursors sadly, unless you do something crazy like hide the cursor ( cursor: none; ), track the mouse position with JavaScript, and display something entirely custom. Um, like this! See the Pen Animation following cursor by tamm (@tamm) on CodePen.
Other examples from around the web
Создаем собственный курсор при помощи CSS и JavaScript
Подпишись на наш канал с тестами по HTML/CSS/JS в Telegram!
Вам случалось зайти на какой-нибудь сайт и просто застыть в восхищении от реализованных на нем разных штучек? Наверняка среди них был и какой-нибудь интересный курсор, отличающийся от обычной стрелочки.
Такой курсор может улучшить пользовательский опыт. Я задумался, как же его создать, и тщательно изучил этот вопрос. Результатом моих изысканий стала эта статья.
Мы рассмотрим два способа создания кастомного курсора мыши: на чистом CSS и с помощью JavaScript. После этого вы сможете создавать собственные курсоры, привлекающие внимание пользователей.
Эта статья ориентирована на начинающих разработчиков, но понимание некоторых вещей у вас уже должно быть. Чтобы создавать собственные курсоры, вам нужно знать HTML, а также основы CSS и JavaScript.
Кастомизация курсора мыши с помощью CSS
Изменить вид курсора при помощи CSS довольно просто, поскольку в CSS для этого есть специальное свойство. Все, что нужно сделать, это познакомиться с ним и использовать.
Фронтенд-разработчики применяют это свойство часто. Называется оно незамысловато — cursor .
Прежде чем перейти к примеру использования свойства cursor на практике, давайте рассмотрим значения, которые оно может принимать. Хотя большинство разработчиков используют лишь несколько самых важных, стоит знать, какие варианты вообще возможны.
Этот пример на CodePen позволяет протестировать разные виды курсоров. Просто наводите мышь на кнопки с подписанными значениями свойства cursor и оценивайте результат.
Но вернемся к нашей теме. Как же нам кастомизировать курсор мыши? Для этого надо просто сообщить CSS, какое изображение вы намерены использовать, и указать путь к нему при помощи значения url свойства cursor .
Из примера видно, что я установил свойство cursor для элемента body , так что оно будет применяться к курсору по всему документу. Нужное изображение указано в url() .
Далее я добавляю еще парочку url() просто на случай, если первая картинка не загрузится или не найдется из-за каких-то внутренних проблем (т. е. это fallback). Сайт, внезапно оставшийся вообще без курсора, — просто кошмар разработчика, так что fallback важен. Вы можете добавить столько запасных URL, сколько хотите.
Вы также можете настроить отдельный курсор для любого элемента или раздела вашего сайта. Пример на CodePen:
Это все о кастомизации курсоров при помощи CSS. Теперь давайте посмотрим, что можно сделать, добавив JavaScript.
Как сделать собственные курсоры мыши с помощью JavaScript
Чтобы использовать в этом деле JavaScript, нужны манипуляции с DOM.
Для начала давайте посмотрим на наш HTML:
Для представления курсора я создал два блока div . Мы будем манипулировать ими из JavaScript.
Но все по порядку. Сперва создадим CSS.
Обратите внимание: в CSS я отключил курсор (помните cursor:none ?). Это сделает курсор невидимым; вместо него будет отображаться наш кастомный курсор.
Я стилизовал блоки div , чтобы придать им курсорообразный вид. Вы можете сделать что-то свое, может, добавить фоновый рисунок, эмодзи, стикеры и т. п.
Как с помощью JavaScript заставить курсоры двигаться
const cursorRounded = document.querySelector('.rounded'); const cursorPointed = document.querySelector('.pointed'); const moveCursor = (e)=> < const mouseY = e.clientY; const mouseX = e.clientX; cursorRounded.style.transform = `translate3d($px, $px, 0)`; cursorPointed.style.transform = `translate3d($px, $px, 0)`; > window.addEventListener('mousemove', moveCursor)
Я добавил прослушиватель событий в глобальном объекте window для прослушки любых движений мыши. Когда мышь двигается, вызывается функциональное выражение moveCursor . В качестве параметра оно получает объект события. При помощи этого параметра я смог получить координаты мыши (X и Y) на любой точке страницы.
Я уже выбрал все виды курсора из DOM при помощи querySelector . Все, что мне оставалось, это перемещать их на точки, определенные координатами X и Y. Это делается путем управления свойствами transform со значением translate3d . В результате, когда движется мышь, блоки div перемещаются в нужные места на странице.
Обратные кавычки, которые вы видите в коде, это шаблонные строки. С их помощью можно легко добавлять переменные к строкам. Альтернативный вариант — конкатенация переменных и строк.
Вот CodePen с кодом и результатом его работы:
Какой метод лучше?
Выбор метода целиком зависит от ваших нужд. Если вам нужно использовать какие-то эмодзи или картинки в качестве курсора — выбирайте CSS. А для кастомизации сложных фигур и управления их движением лучше использовать JavaScript.
Хорош любой способ, позволяющий достичь желаемого результата и поразить посетителей сайта.
How to Create a Custom Mouse Cursor with CSS or JavaScript
Jemima Abu Last updated Apr 6, 2023
Personalizing a website is one of the more fun aspects of web development. In this tutorial, we’ll look at two methods to add a custom mouse cursor to your website.
Back in the early stages of web development, websites ran rampant with all sorts of wacky features: galaxy-themed backgrounds, colorful fonts to the point of illegibility, and marquees galore.
Now we’ve more or less calmed down when it comes to web design but that doesn’t mean we can’t have fun features on our websites anymore. In this tutorial, we’ll look at how to add a personal touch to any website by using a custom cursor, firstly using a CSS-only approach, then a more interactive JavaScript method.
1. Adding a Custom Cursor with CSS
In this demo, we’ve implemented two different cursors on a page using only CSS. Hover over the pen to see what happens:
The CSS property cursor allows us to change our cursor to built-in keywords and it also allows us set an image as the cursor.
Our CSS code looks something like this:
cursor: url("data:image/svg+xml,%3Csvg xmlns='https://www.w3.org/2000/svg' height='16' width='16' style='fill-rule:evenodd;text-rendering:geometricPrecision;image-rendering:optimizeQuality;clip-rule:evenodd;shape-rendering:geometricPrecision' xml:space='preserve' viewBox='0 0 7.5 7.5'%3E%3Cpath d='M0 3.8a3.7 3.7 0 1 1 7.5 0 3.7 3.7 0 0 1-7.5 0zm.5 0a3.3 3.3 0 1 0 6.6 0 3.3 3.3 0 0 0-6.6 0zm2.9 0c0 .2.2.3.4.3a.4.4 0 1 0-.4-.3z' style='fill:currentColor;stroke:currentColor;stroke-width:.0419595'/%3E%3C/svg%3E") 8 8, pointer;