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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10863658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:17:57  来源:igfitidea点击:

Load image with jQuery and append it to the DOM

javascriptjqueryimage

提问by wowpatrick

I'm trying to load an image from a given link

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

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

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

and append it to the page, so I can insert it into a given elementfor an image viewer. Even though I searched Stackoverflowand the jQuerydocs without end, I can't figure it out.

并将其附加到页面,以便我可以将其插入到图像查看器的给定元素中。即使我无休止地搜索了StackoverflowjQuery文档,我也无法弄清楚。

After I load the image, I want to set different values to it, like width, height, etc.

加载图像后,我想为其设置不同的值,例如 width 、 height等。

Update:

更新:

This is what I got. The problem I'm having is that I can't run jQuery functions on the imgelement.

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

});

};

回答by thecodeparadox

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

If you want to do for several images then:

如果你想为多个图像做,那么:

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

Use:

用:

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

回答by George Filippakos

Here is the code I use when I want to preload images before appending them to the page.

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

It is also important to check if the image is already loaded from the cache (for IE).

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

            }
        });
    }

回答by James thompson

var img = new Image();

$(img).load(function(){

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

}).attr({

  src: someRemoteImage

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

回答by Jason Lam

after you get the image path, try either of following ways

获取图片路径后,尝试以下任一方式

  1. (as you need to set more attr than just the src) build the html and replace to the target region

    $('#target_div').html('<img src="'+ imgPaht +'" width=100 height=100 alt="Hello Image" />');
    
  2. you may need to add some delay if changing the "SRC" attr

    setTimeout(function(){///this function fire after 1ms delay
          $('#target_img_tag_id').attr('src',imgPaht);
    }, 1);
    
  1. (因为你需要设置更多的 attr 而不仅仅是 src)构建 html 并替换到目标区域

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

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

回答by Sergey Vakulenko

I imagine that you define your image something like this:

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

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

You can simply load/update image for this tag and chage/set atts (width,height):

您可以简单地加载/更新此标签的图像并更改/设置 atts (width,height):

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

回答by solarbaypilot

With jQuery 3.x use something like:

使用 jQuery 3.x 使用类似的东西:

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