使用jQuery加载图像并将其附加到DOM

时间:2012-06-02 15:39:37

标签: javascript jquery image

我正在尝试从给定的链接加载图片

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

并将其附加到页面,因此我可以将其插入到给定元素中以供图像查看器使用。 即使我无法搜索 Stackoverflow jQuery 文档,我也无法理解。

加载图片后,我想设置不同的值,如宽度,高度等。

更新

这就是我得到的。我遇到的问题是我无法在img元素上运行jQuery函数。

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()

});

};

6 个答案:

答案 0 :(得分:57)

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

如果你想拍几张照片,那么:

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

使用:

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

答案 1 :(得分:16)

以下是我想在将图像附加到页面之前预先加载图片时使用的代码。

检查图像是否已从缓存加载(对于IE)也很重要。

    //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

            }
        });
    }

答案 2 :(得分:14)

var img = new Image();

$(img).load(function(){

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

}).attr({

  src: someRemoteImage

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

答案 3 :(得分:5)

获得图像路径后,请尝试以下方法之一

  1. (因为你需要设置更多attr而不仅仅是src) 构建html并替换到目标区域

    $('#target_div').html('<img src="'+ imgPaht +'" width=100 height=100 alt="Hello Image" />');
    
  2. 如果更改“SRC”attr

    ,您可能需要添加一些延迟
    setTimeout(function(){///this function fire after 1ms delay
          $('#target_img_tag_id').attr('src',imgPaht);
    }, 1);
    

答案 4 :(得分:4)

我想你定义的图像是这样的:

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

您只需加载/更新此标记和chage / set atts(宽度,高度)的图像:

var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);

答案 5 :(得分:0)

使用jQuery 3.x时,请使用类似以下内容:

$('<img src="'+ imgPath +'">').on('load', function() {
  $(this).width(some).height(some).appendTo('#some_target');
});
相关问题