Home  >  Article  >  Web Front-end  >  How to create an inverted text color effect on mouse hover with CSS and JavaScript?

How to create an inverted text color effect on mouse hover with CSS and JavaScript?

DDD
DDDOriginal
2024-10-28 04:10:30231browse

How to create an inverted text color effect on mouse hover with CSS and JavaScript?

Invert Text Color on Mouse Hover

The goal is to invert the color of a text element while hovering over it with a black cursor. The effect should be similar to the following GIF:

[GIF demonstrating the effect]

To achieve this effect with CSS and JavaScript, we'll use a combination of techniques:

  1. Create a duplicate text layer: Duplicate the text element and position it directly on top of the original. Invert the color of the duplicate text layer to white.
  2. Use clip-path to reveal the top layer: Use a clip-path to define a circular area that will reveal the inverted text layer.
  3. Listen for mouse movements: When the user moves the cursor over the text, adjust the clip-path's position to match the cursor's movement.

Here's an example implementation:

<code class="javascript">var h = document.querySelector('h1');
var p = h.getBoundingClientRect();
var c = document.querySelector('.cursor');

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>
<code class="css">body {
  cursor: none;
}

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%));
}

.cursor {
  position: fixed;
  width: 40px;
  height: 40px;
  background: #000;
  border-radius: 50%;
  top: 0;
  left: 0;
  transform: translate(-50%, -50%);
  z-index: -2;
}</code>
<code class="html"><h1 data-text="WORK">WORK</h1>

<span class="cursor"></span></code>

By combining these techniques, we can create the desired text color inversion effect on mouse hover.

The above is the detailed content of How to create an inverted text color effect on mouse hover with CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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