2009-10-29 46 views
3

使用jQuery,我更改點擊圖片天然寬度的jquery

$("#thumb li img").click(function() { 
var newlinkimage = $(this).attr("src"); 

newlinkimage = newlinkimage.substring(14,17); 

    $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg'); 
    $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg'); 

的問題是圖像的src,所述新圖像寬度是,舊的不同。如何獲得新圖像的原始寬度(如在Dreamweaver中獲得該圖像的小箭頭)

回答

3

這是純JavaScript的方式來做到這一點。應該很容易將它集成到你的代碼中。

var newimage = new Image(); 
newimage.src = 'retouche-hr' + newlinkimage + '-a.jpg'; // path to image 
var width = newimage.width; 
var height = newimage.height; 
+1

寬度始終返回0 – menardmam 2009-10-29 15:19:11

+0

確保圖像路徑是實際圖像的有效圖像路徑 – 2009-10-29 16:58:27

+1

當您調用高度/寬度時,圖像必須已經加載。第二行加載圖像,但可能無法通過第3或第4行加載完成加載。 – 2009-10-29 17:09:10

2

舊圖像是否設置了寬度和高度?如果使用$(image).width(「」 )它應該將寬度重新設置爲在對其應用任何寬度更改之前的寬度(類似於高度)。我認爲這對於通過CSS或屬性設置寬度的圖像不起作用。以舊的寬度,您可以使用.outerWidth()來獲取圖像的寬度。

1

想要在改變圖像前獲得圖像的實際寬度,然後將新圖像設置爲該寬度。這與$(img).load:

var pic_real_width; 
var pic_real_height; 

$(img).load(function() { 
    // need to remove these in of case img-element has set width and height 
    $(this).removeAttr("width") 
      .removeAttr("height"); 

    pic_real_width = this.width; 
    pic_real_height = this.height; 
}); 

$("#thumb li img").click(function() { 
var newlinkimage = $(this).attr("src"); 

newlinkimage = newlinkimage.substring(14,17); 

     $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg').width(pic_real_width); 
     $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg').width(pic_real_width); 
+0

會嘗試,現在,看起來不錯! – menardmam 2009-10-29 13:56:04

1

此代碼總是返回零 '0'

var newimage = new Image(); 
    newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; 
    var width = newimage.naturalWidth; 
    var height = newimage.naturalHeight; 
    alert (width); 

WHY ???