How to Invert Text Color on Mouse Hover with CSS and JavaScript?

Susan Sarandon
Release: 2024-10-30 01:29:02
Original
416 people have browsed it

How to Invert Text Color on Mouse Hover with CSS and JavaScript?

Invert Text Color on Mouse Hover

This GIF demonstrates the desired effect:

[GIF of text turning white on mouse hover]

It's possible to create this effect using CSS and JS. One method involves manipulating the clip-path of a duplicated text layer to reveal the inverted color on hover.

<code class="css">h1 {
  color: #000;
  display: inline-block;
  margin: 50px;
  text-align: center;
  position: relative;
}

h1:before {
  position: absolute;
  content: attr(data-text);
  color: #fff;
  background: #000;
  clip-path: circle(20px at var(--x, -100%) var(--y, -100%));
}</code>
Copy after login
<code class="js">document.body.onmousemove = function(e) {
  // Adjust the cursor position
  c.style.left = e.clientX + 'px';
  c.style.top = e.clientY + 'px';

  // Adjust the clip-path
  h.style.setProperty('--x', (e.clientX - p.top) + 'px');
  h.style.setProperty('--y', (e.clientY - p.left) + 'px');
}</code>
Copy after login

When the mouse moves, the script adjusts the clip-path to reveal more of the inverted text, creating the hover effect.

The above is the detailed content of How to Invert Text Color on Mouse Hover with CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template