简体   繁体   English

如果源设置为透明像素,则不显示图像标记背景图像

[英]Image tag background image not showing if source set to transparent pixel

I'm having some trouble displaying a background image on an img tag after setting the src attribute to a transparent pixel. 在将src属性设置为透明像素后,我在img标签上显示背景图像时遇到了一些麻烦。

HTML: HTML:

<img class="test-class" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png">

CSS: CSS:

.test-class {
    border: 1px black solid;
    width: 256px;
    height: 256px;
}

JavaScript: JavaScript的:

var transparentPng = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAE0lEQVR4XgXAAQ0AAABAMP1L38IF/gL+/AQ1bQAAAABJRU5ErkJggg==";
var spriteUrl = "url(http://upload.wikimedia.org/wikipedia/commons/9/9a/Google_Chrome_screenshot.png)"

// Why doesn't background image show?
$(".test-class").attr("src", transparentPng);

// It does show if src is set to a broken URL, though.
//$(".test-class").attr("src", "invalidurl");

$(".test-class").css("background-image", spriteUrl);

Here's a live test case: http://jsfiddle.net/rmjaD/1/ 这是一个实时测试案例: http//jsfiddle.net/rmjaD/1/

What I really want to do is show a sprite, but since the sprite image will be pretty large and it will only be displayed on an event, I'm using the src attribute of the image tag to show an initial image. 我真正想做的是显示一个精灵,但由于精灵图像会非常大并且只会在事件上显示,我使用图像标记的src属性来显示初始图像。 When the event happens, I want to replace that image with the sprite. 当事件发生时,我想用sprite替换该图像。 To achieve this, my idea is to replace the source image with a transparent pixel and set the background image. 为实现这一目标,我的想法是用透明像素替换源图像并设置背景图像。 But for some reason the background image is not showing up. 但由于某种原因,背景图像没有显示出来。

Can you tell me what I need to change in the test case to make the larger image (representing the sprite) visible? 你能告诉我在测试用例中我需要改变什么来使更大的图像(代表精灵)可见吗?

There seems to be something wrong with the image you are using. 您正在使用的图像似乎有问题。

Use this image. 使用此图片。 It works. 有用。

var transparentPng = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=";

base64图像以某种方式损坏,请参阅http://jsfiddle.net/David_Knowles/3SvJU/

var transparentPng = "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM