"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Invert Text Color on Mouse Hover with CSS and JavaScript?

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

Published on 2024-11-11
Browse:531

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.

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

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3