简体   繁体   中英

Can I animate the opacity of a CSS background-image?

CSS/Javascript is not my strong point so I would like to ask if is possible to change the background-image opacity to, let's say, 0.5.

I have a div with

background-image: url(images/nacho312.png);
background-position: -50px 0px;
background-repeat: no-repeat no-repeat;

but when I load a certain view it does not look very good, so I want to have a "half-disolve" effect when that view is shown. Is it possible?

Thanks

Here is a start.

var element = document.getElementById('hello'),
    targetOpacity = 0.5,
    currentOpacity,
    interval = false,


interval = setInterval(function() {

   currentOpacity = element.getComputedStyle('opacity');

   if (currentOpacity > targetOpacity) {
      currentOpacity -= 0.1;
      element.style.opacity = currentOpacity;

   } else {
      clearInterval(interval);
   }


}, 100);

See it on jsFiddle .

Run this on window.onload = function() { } or research cross browser on DOM ready events.

Of course, it is much easier with a library like jQuery.

$(function() {
   $('hello').fadeTo('slow', 0.5);
});

This relies on your container's children inheriting the opacity. To do it without affecting them is a bit of a pain, as you can't reset children's opacity via opacity: 1 .

If you want to animate smoothly and without doing too much extra work - this is a good task for jQuery (or another, similar library).

With jQuery you could do :

$('#id_of_div').fadeTo('fast', 0.5);

To get a fast animated fade effect on the relevant DIV.

Update: if you want to actually fade the background image, but not any foreground contents of the DIV, this is a lot harder. I'd recommend using one container DIV with position:relative and two inner DIVs with position:absolute; . The first of the inner DIVs can have the background image and a lower z-index than the second of the DIVs, and the second DIV would contain any text, etc. to show in foreground. When needed you can call $('#id_of_first_div').fadeTo('fast', 0.5); to fade just the DIV containing the background image.

By the way, the literal answer to your question is "No, you cannot animate the opacity of a CSS background image" - you can only (currently) animate the opacity of a DOM element, not its attributes, thus the need for the above hack.

Other Update: if you want to avoid using any third-party library, you can handle the fade of the background DIV using approach in Alex's answer .

background-image: url(images/nacho312.png);
background-position: -50px 0px;
background-repeat: no-repeat no-repeat;

opacity:0.5; //for firefox and chrome
filter:alpha(opacity=50); //for IE

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