悬停时将图像变为灰色并在鼠标移开时再次变为灰色,HTML5和CSS3。

3

代码已准备就绪,但我希望在鼠标悬停时对图像进行着色(即去除IMG的灰度属性),当鼠标移出时,图像应再次变为灰度。

如果仅通过css无法实现。 javascript也可以,但请不要使用jquery,我不会jquery。

以下是代码:

<style type="text/css">

#ajabox:hover #ajainner{
    height:100px;
    top:-100px;
}

#ajainner{
    width:332px;
    overflow:hidden;
        height:0px;
    background-image:url(../../images/bg_black_50.png);
    position:relative;
    top:-1px;
    transition: top .4s ease-in, height .4s ease-in;
    -ms-transition: top .4s ease-in, height .4s ease-in;
    -webkit-transition: top .4s ease-in, height .4s ease-in;
    -o-transition: top .4s ease-in, height .4s ease-in;
    -moz-transition: top .4s ease-in, height .4s ease-in;
}

#ajabox{
    width:332px;
    margin:0px;
    padding:0px;
    border:0px;
    height:209px
    display:-webkit-box;
    display:box;
    display:-moz-box;
    display:-ms-box;
    display:-o-box;
    overflow:hidden;
}
span{
     color:#FFF; 
     font-family:Verdana, Geneva, sans-serif; 
     left:10px; 
     top:10px; 
     position:relative;
}
img.desaturate { 
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: url(desaturate.svg#greyscale);
    -webkit-filter: grayscale(1);
    filter: gray;
}

</style>
<script type="text/javascript">
</script>
<body bgcolor="#000000">
<div id="ajabox">
    <img src="http://fc03.deviantart.net/fs70/f/2011/123/c/9/adam_jensen__s_army_____________by_gtanmay-d3fh5pw.png" style="width:332px;" class="desaturate"/>
    <div id="ajainner">
        <span>Adam Jensen's Army</span>
        <br />
        <span style="font-size:12px">Made from the CD cover of "Assassin's Creed: Brotherhood"<br />Feat. Adam Jensen(Deus Ex: Human Revolution)</span>
    </div>
</div>
1个回答

9
img { /* Universal settings */
    -webkit-transition:all .4s;
    -moz-transition:all .4s;
    -ms-transition:all .4s;
    -o-transition:all .4s;
    transition:all .4s;
}
img:not(:hover) {
    -webkit-filter:grayscale(100%);
    -moz-filter:grayscale(100%);
    -ms-filter:grayscale(100%);
    -o-filter:grayscale(100%);
    filter:grayscale(100%);
}
img:hover {
    -webkit-filter:grayscale(0%);
    -moz-filter:grayscale(0%);
    -ms-filter:grayscale(0%);
    -o-filter:grayscale(0%);
    filter:grayscale(0%);
}

在老版本的浏览器中,:not选择器可能无法正常工作,但是filter也同样存在兼容性问题,因此这并不是一个很大的问题。

示例代码。


哦,出了问题...所有其他图像都有鼠标悬停时的去饱和度和饱和度属性...但是使用我提供的代码不起作用:( - user1328586
如果你想让它能够与你提供的示例一起使用,只需将img更改为你要定位的任何元素。在你的情况下,它将是img.desaturate吗?所以img.desaturate、img.desaturate:not(:hover)和img.desaturate:hover。 - ddhboy
遗憾的是,这个解决方案在IE10及以上版本上不起作用。 - muffir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接