首頁  >  文章  >  web前端  >  如何在 CSS 中實現灰階背景圖像的跨瀏覽器相容性?

如何在 CSS 中實現灰階背景圖像的跨瀏覽器相容性?

Susan Sarandon
Susan Sarandon原創
2024-10-25 19:15:59707瀏覽

How can I achieve cross-browser compatibility for grayscale background images in CSS?

CSS 中的灰階背景影像

問題:

問題:

實現淡入淡出的跨入淡出的跨入淡出的跨入中。瀏覽器支援CSS 背景影像轉灰度仍然是一個挑戰。雖然 CSS3 濾鏡灰階效果在 Chrome 和 Safari 等現代瀏覽器中有效,但在 Firefox、IE 和行動瀏覽器等舊版瀏覽器中卻失敗。

解決方案:

使用SVG 濾鏡:
<code class="svg"><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">/</feColorMatrix>
</filter>
</svg></code>

該濾鏡涉及使用SVG 濾鏡,它提供了一種跨瀏覽器的方法來應用顏色轉換。此技術涉及使用以下SVG 過濾器建立資料URL:
<code class="css">.grayscale {
  -webkit-filter: grayscale(100%);
  filter: gray;
  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");
}</code>

透過使用filter 屬性將此濾鏡應用於背景影像,我們可以實現灰階效果:

使用jQuery 動態切換:
<code class="jquery">$(document).ready(function () {
  $("#image").mouseover(function () {
    $(".nongrayscale").removeClass().fadeTo(400, 0.8).addClass("grayscale").fadeTo(400, 1);
  });
  $("#image").mouseout(function () {
    $(".grayscale").removeClass().fadeTo(400, 0.8).addClass("nongrayscale").fadeTo(400, 1);
  });
});</code>

要動態切換灰階效果,可以使用jQuery:

IE10-11 相容性:
<code class="svg"><svg>
  <defs>
    <filter xmlns="http://www.w3.org/2000/svg" id="desaturate">
      <feColorMatrix type="saturate" values="0" />
    </filter>
  </defs>
  <image xlink:href="http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg" width="600" height="600" filter="url(#desaturate)" />
</svg></code>
IE10-11 相容性:IE10-11 相容性:IE10-11 相容性: 對於IE10-11,由於瀏覽器渲染的變化,需要另一種方法。以下 SVG 濾鏡可用於去飽和,達到類似的灰階效果:

以上是如何在 CSS 中實現灰階背景圖像的跨瀏覽器相容性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn