簡體   English   中英

如何用相同大小的矩形替換圖像

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

如何隱藏圖像,但要保留邊框或不透明矩形在該圖像所在的位置? 遮蓋圖像也是可以的。

這必須適用於不同大小的圖像,因此對包含div的大小進行硬編碼並設置border / bgcolor無效。

我想我可以等待圖像加載,獲取圖像的尺寸,然后將其包含的div設置為相同的尺寸。 有沒有更簡單的方法?

如果只想保留空間,直到圖像加載完畢,請使用CSS可見性屬性並將圖像可見性設置為hidden

.image {
    visibility: hidden;
}

盡管圖像不可見,但仍會占用空間,以防止布局崩潰。 當然,不會顯示任何圖像邊框,但是我猜您這樣做只是為了在隱藏圖像后防止布局崩潰。

給定服務器上URL'images / opaque.gif'的1x1像素,您可以執行以下操作:

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

必須設置寬度和高度,以便圖像不會調整為1x1。

將圖像放入容器中並居中以模仿圖像的邊界。 然后根據需要淡出圖像(這里的opacity屬性非常好)或將其visibility屬性設置為hidden

這適用於任何類型的圖像,只是不為容器設置寬度和高度。 使用padding來獲得所需的邊界。

簡單的方法包括將CSS opacity設置為0 ,或將visibilityhidden

如果要用相同大小的元素替換它,怎么辦

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM