Home  >  Article  >  Web Front-end  >  How to Easily Change an Image on Click with CSS?

How to Easily Change an Image on Click with CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 17:38:02986browse

How to Easily Change an Image on Click with CSS?

Change an Image on Click with Ease

Tired of the complex JS code required to change an image on click? Explore a simpler solution using pseudo selectors or the .active class.

Understanding the Solution

To change an image on click without extensive JS code, you can leverage the following techniques:

  • Pseudo Selectors: You can create a pseudo selector that targets the element on click and styles it with a different image using CSS.
  • .active Class: By applying the .active class to the target element on click, you can use CSS to display the desired image.

Implementing the Solution

Using Pseudo Selectors:

li:hover img, li:active img {
    display: none;
}

li:hover img#new_image, li:active img#new_image {
    display: block;
}

Using .active Class:

  1. Add the .active class to the target list element: li.active.
  2. Define the CSS rule for this class:
li.active img {
    display: none;
}

li.active img#new_image {
    display: block;
}

Example Code with .active Class:

<ul>
  <li><img>

Note: Remember to add the appropriate click event listener or use inline onclick attributes to trigger the change.

The above is the detailed content of How to Easily Change an Image on Click with CSS?. 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