css - 如何将图像设为黑/白,然后在 Safari 中悬停时上色?

标签 css

如何在 Safari 和所有浏览器中将图像变为黑/白,然后在悬停时着色?

img.grayscale {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 10+ */
    filter: gray; /* IE6-9 */
    -webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
    -webkit-transition: all .6s ease; /* Fade to color for Chrome and Safari */
    -webkit-backface-visibility: hidden; /* Fix for transition flickering */
}

img.grayscale:hover {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
    -webkit-filter: grayscale(0%);
}

http://jsfiddle.net/KDtAX/487/

此代码在 Safari 中不起作用。

最佳答案

我找到了一个适用于 Google Chrome、Safari 6+ 和 Opera 15+ 的解决方案。只需将以下代码复制并粘贴到您的 CSS 文件中即可:

  1. 首先,将所有彩色图像转为黑白图像(100% 灰色);
  2. 然后,当您将鼠标悬停在上面时,将图像变回彩色。

    img {
        filter: grayscale(100%);
        -webkit-filter: grayscale(100%);
    }
    
    img:hover {
        filter: none;
        -webkit-filter: grayscale(0);
    }
    

如果您只想将此效果应用于一张图像:

  1. 首先,在您的 HTML 文件中为该图像指定一个唯一 ID。例如:

    <img src="img/stefets-picture.png" id="stefets-picture" alt="stefets's picture">
    
  2. 然后,在您的 CSS 文件中为该 ID 定义 CSS 规则:

    #stefets-picture {
        filter: grayscale(100%);
        -webkit-filter: grayscale(100%);
    }
    
    #stefets-picture:hover {
        filter: none;
        -webkit-filter: grayscale(0);
    }
    

希望对您有所帮助,

菜谱

关于css - 如何将图像设为黑/白,然后在 Safari 中悬停时上色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16333972/

相关文章:

html - 需要修复导航栏

html - 如何将标题放在图像下方的一行中?

css - 在悬停按钮时在按钮上添加渐变而不影响文本

css - textarea 调整父 div 容器的大小

css - 当行内的单元格具有类名时,为什么 CSS 悬停在表格行上不起作用?

html - 为什么导航栏不会按照指示划到 100% 宽度?

javascript - 在 Canvas 上绘制背景图像

css 伪类选择器

html - IE11 中的 Flex : width100% not working with nested flex and direction 'column'

html - 使用 Flexbox 重新定位选择器