IE6 PNG transparency

前端 未结 12 2155
耶瑟儿~
耶瑟儿~ 2020-11-28 08:26

How can I fix PNG transparency bug in IE6 for background image?

12条回答
  •  感情败类
    2020-11-28 08:42

    Ok, I'm virtually new to html/js but I think I had to change Rob Allen's answer a bit to fix two problems:

    1. AlphaImageLoader() was changing the aspect ratio of my images so I needed to restore the original sizes AFTER the images were loaded.
    2. fixPngs(), if called from the end of the html, was being called after the document was loaded but before all the images were loaded.

    So I've changed my fixPngs() to just attach an event:

    function fixPngs() {
      // Loops through all img tags
      for(i = 0; i < document.images.length; i++) {
        var u = document.images[i].src;
        var o = document.images[i];
    
        if(u.indexOf('.png') > 0) {
          o.attachEvent('onload', fixPng);
          o.src = u;
        }
      }
    }
    

    fixPngs() is still being called from the end of the html:

    
    

    And fixPng() now fetches the caller, detaches the event, saves the original dimensions, calls AlphaImageLoader() and finally restores the dimensions:

    // u = url of the image
    // o = image object
    function fixPng(e) {
      var caller = e.target            ||
                   e.srcElement        ||
                   window.event.target ||
                   window.event.srcElement;
      var u = caller.src;
      var o = caller;
    
      if(!o || !u)
        return;
    
      // Detach event so is not triggered by the AlphaImageLoader
      o.detachEvent('onload', fixPng);
    
      // Save original sizes
      var oldw = o.clientWidth;
      var oldh = o.clientHeight;
    
      // Need to give it an image so we don't get the red x
      o.src          = 'images/spacer.gif';
      o.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+ u +"', sizingMethod='scale')";
    
      // Restore original sizes
      if(o.style) {
        o.style.width  = oldw +"px";
        o.style.height = oldh +"px";
      }
    }
    

    Have I overkilled it?

提交回复
热议问题