简体   繁体   中英

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.

You can do this without using two images. Instead use CSS filter to make the first image black&white.

 img { -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */ filter: grayscale(100%); } img:hover { -webkit-filter: none; filter: none; transition: 0.66s }
 <img src="https://www.w3schools.com/howto/pineapple.jpg" alt="Pineapple" width="300" height="300">

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM