CSS transparent background fallback when images ar

2019-08-01 07:31发布

I have a DIV with a transparent PNG background applied to it. Is there a way (use of JS is fine) for me to:

  1. Have the transparency effect when images are enabled
  2. Apply a normal solid background color to it when images are disabled

5条回答
▲ chillily
2楼-- · 2019-08-01 07:46

I think you are looking for a

jQuery lightbox

like thing.

查看更多
Root(大扎)
3楼-- · 2019-08-01 07:47

As I remember, if you set background-color and background-image, that would not work with transparent PNGs (over the transparency you will see background-color). Te solution is to use a special css class:

.trans_back { background:red }
DIV#trans_png { background:url(reddot.png); position:absolute; left:-9px; }

Then make a script:

$().ready(function(){
  $('#trans_png').load(function(){
    $('.tans_back').css('background',$(this).css('background'));
  });
});

DIV#trans_png is used to check if image is loaded, you can do it in way you like, I prefer simplest without scripting.

查看更多
混吃等死
4楼-- · 2019-08-01 07:47

This is based on Thinker's post, but I found it didn't work.

I found that $('#trans_png').load didn't trigger (jquery 1.9.1, firefox) - I had to use the load event of an image's src, ie, $('#logo img').attr('src', 'images/layout/logo.png').load(function() {. Any image will do.

I also found that just copying the background didn't work, I had to explicitly clear the color and add the image url.

I also had to apply this change to several elements (sub-menu uls), so added a loop within the load function:

$('#logo img').attr('src', 'images/layout/logo.png').load(function() {
    $("ul.MenuBarHorizontal ul").each(function() {
        $(this).css('background-color','none').css('background','none').css('background', $('#menu-trns-bg').css('background-image'));
    });
}); 

This is essentially Thinker's answer, fixed, however I couldn't fit this intelligibly into a comment.

Just to clarify, the ULs by default have background-color: white;, and the div is positioned off screen div#menu-trns-bg {position: absolute;left:-3000px;background-image:url(../images/layout/body-bg.png);} I'm using this on a Spry menu.

查看更多
闹够了就滚
5楼-- · 2019-08-01 07:50

You should be able to supply both a css background-image and background-color. If images are disabled the color should still show up.

查看更多
狗以群分
6楼-- · 2019-08-01 07:57

Another solution that comes to my mind is that you could set up a solid background by default, then load the image(s) with JavaScript and apply transparency. If someone will have JS disabled or image download will fail then you will have the default solid background.

查看更多
登录 后发表回答