2012-06-02 4 views
32

Ich versuche, ein Bild von einem bestimmten LinkBild laden mit jQuery und hängen Sie es an die DOM

var imgPath = $(imgLink).attr('href');

und hängen Sie ihn an die Seite zu laden, so kann ich es in einem gegebenen einfügen Element für einen Bildbetrachter. Obwohl ich Stackoverflow und die jQuery Dokumente ohne Ende suchte, kann ich es nicht herausfinden.

Nachdem ich das Bild zu laden, möchte ich verschiedene Werte, um es zu setzen, wie Breite, Höhe usw.

Update:

Dies ist, was ich bekam. Das Problem, das ich habe, ist, dass ich jQuery Funktionen auf dem img Element nicht ausführen kann.

function imagePostition(imgLink) { 

// Load the image we want to display from the given <a> link  
// Load the image path form the link 
var imgPath = $(imgLink).attr('href'); 

// Add image to html 
$('<img src="'+ imgPath +'" class="original">').load(function() { 

    $(imgLink).append(this); 

    var img = this; 

    // Resize the image to the window width 
    // http://stackoverflow.com/questions/1143517/jquery-resizing-image 

    var maxWidth = $(window).width();  // window width 
    var maxHeight = $(window).height();  // window height 
    var imgWidth = img.width;    // image width 
    var imgHeight = img.height;    // image height 
    var ratio = 0;       // resize ration 
    var topPosition = 0;     // top image position 
    var leftPostition = 0;     // left image postiton 

    // calculate image dimension 

    if (imgWidth > maxWidth) { 
     ratio = imgHeight/imgWidth; 
     imgWidth = maxWidth; 
     imgHeight = (maxWidth * ratio); 
    } 
    else if (imgHeight > maxHeight) { 
     ratio = imgWidth/imgHeight; 
     imgWidth = (maxHeight * ratio); 
     imgHeight = maxHeight; 
    } 

    // calculate image position 

    // check if the window is larger than the image 
    // y position 
    if(maxHeight > imgHeight) { 
     topPosition = (maxHeight/2) - (imgHeight/2); 
    } 
    // x position 
    if(maxWidth > imgWidth) { 
     leftPostition = (maxWidth/2) - (imgWidth/2); 
    } 

    $(imgLink).append(img); 

    // Set absolute image position 
    img.css("top", topPosition); 
    img.css("left", leftPostition); 

    // Set image width and height 
    img.attr('width', imgWidth); 
    img.attr('height', imgHeight); 

    // Add backdrop 
    $('body').prepend('<div id="backdrop"></div>'); 

    // Set backdrop size 
    $("#backdrop").css("width", maxWidth); 
    $("#backdrop").css("height", maxHeight); 

    // reveal image 
    img.animate({opacity: 1}, 100) 
    img.show() 

}); 

}; 

Antwort

55
$('<img src="'+ imgPath +'">').load(function() { 
    $(this).width(some).height(some).appendTo('#some_target'); 
}); 

Wenn Sie möchten, dann mehrere Bilder tun:

function loadImage(path, width, height, target) { 
    $('<img src="'+ path +'">').load(function() { 
     $(this).width(width).height(height).appendTo(target); 
    }); 
} 

Verwendung:

loadImage(imgPath, 800, 800, '#some_target'); 
+0

Wenn ich dann Eigenschaften aus dem Bild, wie seine Höhe und Breite, erhalten möchte, wie kann ich es bekommen? '$ ('') .load (function() {var img = $ (this); ...' scheint nicht zu funktionieren – wowpatrick

+12

Können wir aufhören, den Elefanten im Raum zu ignorieren - imgPath wird falsch geschrieben – sq2

+4

@ sq2..hi mate ... check den Elefanten 'imgPaht' in OPs Beitrag und kommentiere .. thx':) ' – thecodeparadox

5

, nachdem Sie den Bildpfad zu erhalten, versuchen entweder von folgenden Möglichkeiten

  1. bauen die HTML und ersetzen zu der Zielregion

    $('#target_div').html('<img src="'+ imgPaht +'" width=100 height=100 alt="Hello Image" />'); 
    
  2. müssen Sie möglicherweise eine Verzögerung hinzufügen, wenn die Änderung der „SRC“ attr

    (wie Sie mehr attr setzen als nur die src benötigen)
    setTimeout(function(){///this function fire after 1ms delay 
         $('#target_img_tag_id').attr('src',imgPaht); 
    }, 1); 
    
4

ich stelle mir vor, dass Sie Ihr Bild etwas wie folgt definieren:

<img id="image_portrait" src="" alt="chef etat" width="120" height="135" /> 

Sie können einfach laden/aktualisieren Bild für dieses Tag und chage/set atts (Breite, Höhe):

var imagelink; 
var height; 
var width; 
$("#image_portrait").attr("src", imagelink); 
$("#image_portrait").attr("width", width); 
$("#image_portrait").attr("height", height); 
11
var img = new Image(); 

$(img).load(function(){ 

    $('.container').append($(this)); 

}).attr({ 

    src: someRemoteImage 

}).error(function(){ 
    //do something if image cannot load 
}); 
+0

Dies erstellt und Element.Lädt es und hängt es dann an das DOM an. Es funktioniert jedes Mal einwandfrei für mich. –

+2

Benötigt ein Leerzeichen zwischen new und Image(); –

+0

jQuery empfiehlt, den Fehlerhandler vor dem Festlegen der src https://api.jquery.com/error/ zu setzen. Auch .error() ist jetzt veraltet, also besser .on ("error", ... – josef

13

Hier ist der Code, den ich benutze, wenn ich Bilder vorzuladen wollen, bevor sie an die Anfügen Seite.

Es ist auch wichtig zu prüfen, ob das Image bereits aus dem Cache (für IE) geladen ist.

//create image to preload: 
    var imgPreload = new Image(); 
    $(imgPreload).attr({ 
     src: photoUrl 
    }); 

    //check if the image is already loaded (cached): 
    if (imgPreload.complete || imgPreload.readyState === 4) { 

     //image loaded: 
     //your code here to insert image into page 

    } else { 
     //go fetch the image: 
     $(imgPreload).load(function (response, status, xhr) { 
      if (status == 'error') { 

       //image could not be loaded: 

      } else { 

       //image loaded: 
       //your code here to insert image into page 

      } 
     }); 
    } 
Verwandte Themen