Search code examples
cssopacityphotoshoplayer

how to change the opacity of the top image layer with css?


I have an image with 2 states: normal state with black and white and hover state with colors, in photoshop I've made 2 layers: background layer and top layer, I want the background layer to be shown as normal state and when hovering it shows the top layer. is there a way to apply the opacity CSS option just to the top layer? so as I can make it 0 in normal state and 1 in hover? or I need to make 2 images and show the second one instead of the first one in hover?

I've tried tiff extension which save the layers but when changing the opacity to 0 the image turns dark, that means the opacity is applied to all the layers.


Solution

  • I've found this solution with JavaScript: the normal state file: 1.png the hover state file: 1.png.png

    <img id="my-img" alt="" src="1.png"
    onmouseover="hover(this);" onmouseout="unhover(this);" />
    <script>
    function hover(element) {
    element.setAttribute('alt', element.src );
    element.setAttribute('src', element.src  +'.png');
    }
    
    function unhover(element) {
    element.setAttribute('src', element.alt);
    }
    </script>