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

2023-12-04

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

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

并将其附加到页面上,这样我就可以将其插入到给定元素中对于图像查看器。 尽管我搜索过堆栈溢出jQuery文档没有尽头,我无法弄清楚。

加载图像后,我想设置不同的值,如宽度、高度, etc.

Update:

这就是我得到的。我遇到的问题是我无法在img元素。

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

});

};

$('<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);
    });
}

Use:

loadImage(imgPath, 800, 800, '#some_target');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 jQuery 加载图像并将其附加到 DOM 的相关文章