开发者

How can I replace an image with rectangle of the same size

How can I hide an image, but keep a border or opaque rectangle where the image used to be? Masking the image is acceptable too.

This has to work for images of diffe开发者_如何转开发rent sizes, so hardcoding a containing div's size and setting a border/bgcolor won't work.

I guess I could wait for the image to load, get it's dimensions, and then set its containing div to the same dimensions. Is there an easier way though?


If you just want to retain space until the image is loaded use the CSS visibility attribute and set the image visibility to hidden.

.image {
    visibility: hidden;
}

The image is still going to take up space despite its invisible preserving your layout from collapsing. Of course no image borders will be displayed but I am guessing you are doing this only to preserve layout from collapsing after the image is hidden.


Put the image into a container and center it to mimic the image's border. Then fade out the image as you like (the opacity property is perfectly fine here) or set its visibility property to hidden.

This works for any kind of image, just do not set a width and height for the container. Use padding to achieve the desired borders.


Given a 1x1 pixel on your server at URL 'images/opaque.gif', you could do this:

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

Setting the width and height is necessary so the image doesn't resize to 1x1.


Easy methods include setting CSS opacity to 0, or visibility to hidden.

If you want to replace it with an element of the same size, how about

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'));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜