2011-08-02 51 views
0

如何隐藏图像,但保留一个边框或不透明的矩形,图像曾经是?掩盖图像也是可以接受的。如何用相同尺寸的矩形替换图像

这必须适用于不同大小的图像,因此硬编码包含div的大小和设置border/bgcolor将不起作用。

我想我可以等待图像加载,得到它的尺寸,然后将其包含的div设置为相同的尺寸。有没有更简单的方法?

回答

1

将图像放入容器并将其居中以模仿图像的边框。然后根据需要淡出图像(此处的opacity属性完全正常)或将其visibility属性设置为hidden

这适用于任何形式的图像,只是不设置容器的宽度和高度。使用padding来实现所需的边界。

+0

很多好的答案在这里,但我也接受你回答问题的边界部分。顺便说一下,容器可能需要设置为显示:inline-block才能使其具有相同的图像大小。 – pepsi

1

鉴于你在URL“图像/ opaque.gif”服务器上的1x1像素,你可以这样做:

var theImage = $('img'); 
theImage 
    .css({width: theImage.width(), height: theImage.height()}) 
    .attr('src', 'images/opaque.gif'); 

设置宽度,因此图像不调整到1x1的高度是必要的。

1

简单的方法包括设置CSS opacity0visibilityhidden

如果你想用同样大小的元素,如何

function hideImage(image) { 
    var s = getComputedStyle(image, null); 
    var w = s.getPropertyValue("width"); 
    var h = s.getPropertyValue("height"); 
    var d = document.createElement('div'); 
    /* do your supplementary styling, e.g. background in CSS */ 
    /* by default, img elements are display: inline-block;, by the way */ 
    d.className = 'imagecover'; 
    d.style.width = w; 
    d.style.height = h; 
    image.parentNode.replaceChild(d, image); 
} 

hideImage(document.getElementById('some_image_to_hide')); 
2

如果你只是想,直到图像加载使用CSS visibility attribute保留空间和图像的可见性设置为hidden来取代它。

.image { 
    visibility: hidden; 
} 

尽管图像看起来不可见,但仍然会占用空间,因此无法保持布局不受损坏。当然,没有图像边框会显示,但我猜你只是为了在隐藏图像后保留布局而不进行折叠。

相关问题