使用jQuery加载图像并将其附加到DOM [英] Load image with jQuery and append it to the DOM
本文介绍了使用jQuery加载图像并将其附加到DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从给定的链接加载图片
I'm trying to load an image from a given link
var imgPath = $(imgLink).attr('href') ;
并将其附加到页面,因此我可以将其插入到给定元素中以供图像查看器使用。
即使我搜索 Stackoverflow 和 jQuery 文档没有结束,我也无法理解。
and append it to the page, so I can insert it into a given element for an image viewer. Even though I searched Stackoverflow and the jQuery docs without end, I can't figure it out.
加载图片后,我想设置不同的值,如宽度,高度等。
After I load the image, I want to set different values to it, like width, height, etc.
更新:
这就是我得到的。我遇到的问题是我无法在 img
元素上运行jQuery函数。
This is what I got. The problem I'm having is that I can't run jQuery functions on the img
element.
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');
});
如果你想拍几张照片,那么:
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);
});
}
使用:
loadImage(imgPath, 800, 800, '#some_target');
这篇关于使用jQuery加载图像并将其附加到DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文