Home  >  Article  >  Web Front-end  >  How to Achieve an Inverted Text Color Hover Effect Using CSS Clip-paths and JavaScript?

How to Achieve an Inverted Text Color Hover Effect Using CSS Clip-paths and JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 03:51:30757browse

How to Achieve an Inverted Text Color Hover Effect Using CSS Clip-paths and JavaScript?

Invert Text Color on Mouse Hover Using CSS and JavaScript

To achieve the desired hover effect, where black text inverts to white while maintaining the appearance of a black cursor, we can combine the capabilities of CSS clip-paths with JavaScript event handling.

The approach consists of creating two layers of text: the primary text layer and an inverted text layer. The inverted text layer is positioned behind the primary text layer and has its text color set to white.

Using JavaScript, we capture the mouse movement and dynamically adjust the clip-path of the inverted text layer. As the mouse moves, the clip-path is adjusted to reveal more of the inverted text, creating the illusion of the primary text inverting its color.

Here's a breakdown of the key code components:

<code class="css">/* Primary Text Layer */
h1 {
  color: #000;
  position: relative;
}

/* Inverted Text Layer */
h1:before {
  position: absolute;
  content: attr(data-text); /* Same text as primary layer */
  color: #fff;
  background: #000;
  clip-path: circle(0 at var(--x, -100%) var(--y, -100%)); /* Dynamic Clip-path */
}

/* Cursor */
.cursor {
  position: fixed;
  width: 40px;
  height: 40px;
  background: #000;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  z-index: -2;
}</code>
<code class="javascript">// Event Listener for Mouse Movement
document.body.onmousemove = function(e) {
  // Update cursor position
  cursor.style.left = e.clientX + 'px';
  cursor.style.top = e.clientY + 'px';

  // Update clip-path of inverted layer based on mouse position
  h1.style.setProperty('--x', (e.clientX - p.top) + 'px');
  h1.style.setProperty('--y', (e.clientY - p.left) + 'px');
};</code>

Example Code:

<code class="html"><h1 data-text="WORK">WORK</h1>
<span class="cursor"></span></code>

Result:

When you hover over the "WORK" text, the black text will gradually transition to white as the mouse cursor moves.

The above is the detailed content of How to Achieve an Inverted Text Color Hover Effect Using CSS Clip-paths 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