簡體   English   中英

獲取動態圖像的寬度和高度

[英]Getting width and height of a dynamic image

我在隱藏的div中嵌入了一個img標簽。 當用戶單擊具有圖像名稱的動態超鏈接時,圖像必須以模態 window 顯示。 要將 div 定位在模態 window 內,需要圖像高度。 但是當點擊超鏈接時,在分配src之后,高度變為0 所以圖像不能在中間對齊。 請幫助我在瀏覽器中顯示圖像之前獲取圖像的寬度。

<div id="imgFullView" class="modal_window imgFullView">
    <img alt="Loading..." id="imgFull" />
</div>

function ShowImage(imgSrc) {
    $("#imgFull").attr("src", imgSrc);
    alert($("#imgFull").height());
    $("#imgFullView").width($("#imgFull").width());
    $("#imgFullView").height($("#imgFull").height());
    show_modal('imgFullView', true);
}

showimage方法將被稱為超鏈接的onclick 提前致謝...

經過您的專業指導,對我有用的解決方案...

 function ShowImage(imgSrc) {
    $("#imgFull").removeAttr("src"); //To remove the height and width of previously showed imaged from img tag.
    $("#imgFull").attr("src", imgSrc);
    $("#imgFullView").width(document.getElementById("imgFull").width);
    $("#imgFullView").height(document.getElementById("imgFull").height);
    show_modal('imgFullView', true);
 }

嘗試這個。

    var img = $("imgFull")[0]; // Get my img elem
    var real_width, real_height;
    $("<img/>") // Make in memory copy of image to avoid css issues
        .attr("src", $(imgFull).attr("src"))
        .load(function() {
            real_width = this.width;   // Note: $(this).width() will not
            real_height = this.height; // work for in memory images.
        });

謝謝。

嗯,問題是您無法知道尚未加載的圖像的大小。 嘗試這個:

function ShowImage(imgSrc) {
  $("#imgFull").attr("src", imgSrc);
  $("#imgFull").load(function(){  //This ensures image finishes loading
     alert($("#imgFull").height());
     $("#imgFullView").width($("#imgFull").width());
     $("#imgFullView").height($("#imgFull").height());
     show_modal('imgFullView', true);
  });
}

使用.load()我們確保圖像在嘗試獲取其 size() 之前完成加載

希望這可以幫助。 干杯

這在過去對我有用:

function ShowImage(imgSrc){
 $('<img id="imgFull" />').bind('load',
    function(){
        if ( !this.complete || this.naturalWidth == 0 ) {
            $( this ).trigger('load');      
        } else {
            $( this ).appendTo('#imgFullView')
$('#imgFullView').width(this.naturalWidth).height(this.naturalHeight);
        }    
    }).attr("src",imgSrc);   
}

$(document).ready(function(){ ShowImage('http://www.google.com/images/logos/ps_logo2.png') });

演示在這里:

http://jsfiddle.net/jyVFc/4/

暫無
暫無

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

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