Home  >  Q&A  >  body text

CSS only method to dynamically modify image src on click without using JavaScript

I need to change the src of an image on mouse click using only css like

img:active {
}

P粉799885311P粉799885311217 days ago603

reply all(1)I'll reply

  • P粉238433862

    P粉2384338622024-04-07 10:34:46

    You can achieve this by using a element replacing the function content attribute.

    Please note that you cannot set up any ARIA or other accessibility-related features using this technology, so the information you convey may be lost to parts of the user base. (This may be illegal depending on what the information is, who you are, and the control you are in/marketed to).

    You may want to set tabindex or wrap the image in a button to make it accessible via keyboard/etc.

    Also note that :active means "on click" not "after click". CSS has no "after click" pseudo-class (although :focus is sufficient in some cases).

    img:active {
        content: url(http://placekitten.com/200/200);
    }
    <img src="http://placekitten.com/g/200/200" alt="">

    reply
    0
  • Cancelreply