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

wow*_*ick 38 javascript jquery image

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

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

并将其附加到页面,因此我可以将其插入到图像查看器的给定元素中.即使我搜索StackoverflowjQuery文档没有结束,我无法弄明白.

加载图像后,我想为它设置不同的值,如宽度,高度等.

更新:

这就是我得到的.我遇到的问题是我无法在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()

});

};
Run Code Online (Sandbox Code Playgroud)

the*_*dox 58

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

如果你想为几张图片做,那么:

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

使用:

loadImage(imgPath, 800, 800, '#some_target');
Run Code Online (Sandbox Code Playgroud)

  • 我们可以停止忽略房间里的大象 - imgPath拼写错误.谢谢. (13认同)
  • @ sq2..hi mate ...在OP的帖子中检查大象`imgPaht`并发表评论.. thx`:)` (5认同)
  • 在jQuery 3.x中不再起作用/崩溃并报错:TypeError:e.indexOf不是函数 (2认同)

Geo*_*kos 17

这是我在将图像附加到页面之前预先加载图像时使用的代码.

检查图像是否已从缓存加载(对于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

            }
        });
    }
Run Code Online (Sandbox Code Playgroud)


小智 14

var img = new Image();

$(img).load(function(){

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

}).attr({

  src: someRemoteImage

}).error(function(){
  //do something if image cannot load
});
Run Code Online (Sandbox Code Playgroud)

  • 需要new和Image()之间的空格; (2认同)

小智 5

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

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

    $('#target_div').html('<img src="'+ imgPaht +'" width=100 height=100 alt="Hello Image" />');
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果更改"SRC"attr,您可能需要添加一些延迟

    setTimeout(function(){///this function fire after 1ms delay
          $('#target_img_tag_id').attr('src',imgPaht);
    }, 1);
    
    Run Code Online (Sandbox Code Playgroud)


Ser*_*nko 5

我想你是这样定义你的形象的:

<img id="image_portrait" src="" alt="chef etat"  width="120" height="135"  />
Run Code Online (Sandbox Code Playgroud)

您可以简单地加载/更新此标签的图像并更改/设置属性(宽度,高度):

var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);
Run Code Online (Sandbox Code Playgroud)