Home  >  Article  >  Web Front-end  >  How to Achieve Cross-Browser Greyscale Effects on CSS Background Images?

How to Achieve Cross-Browser Greyscale Effects on CSS Background Images?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 09:39:02568browse

How to Achieve Cross-Browser Greyscale Effects on CSS Background Images?

Cross-Browser Solution for Fading CSS Background Images to Greyscale

Despite the availability of the CSS3 filter, applying greyscale effects to background images remains a challenge across different browsers. The solution using SVG filter works for Safari and Chrome, but not for other browsers.

To overcome this limitation, an alternative approach is to use inline SVG code to create a custom filter. This method is compatible with all modern browsers including IE10 and 11.

Code Sample for IE10-11:

<code class="html"><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>

jQuery Solution for Toggling Greyscale Effect:

If you want to dynamically toggle the greyscale effect, you can use jQuery:

<code class="html"><div id="image" class="nongrayscale">
  rollover this image to toggle grayscale
</div></code>
<code class="javascript">$(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>

The above is the detailed content of How to Achieve Cross-Browser Greyscale Effects on CSS Background Images?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn