Загрузите изображение с помощью jQuery и добавьте его в DOM
Я пытаюсь загрузить изображение по заданной ссылке
var imgPath = $(imgLink).attr('href');
и добавить его на страницу, чтобы я мог вставить его в данный элемент для просмотра изображений. Несмотря на то, что я искал Stackru и документы JQuery без конца, я не могу понять это.
После загрузки изображения я хочу установить для него различные значения, такие как ширина, высота и т. Д.
Обновить:
Это то, что я получил. Проблема в том, что я не могу запустить функции jQuery на 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://stackru.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()
});
};
5 ответов
$('<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');
Вот код, который я использую, когда хочу предварительно загрузить изображения перед добавлением их на страницу.
Также важно проверить, загружено ли изображение из кеша (для 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
}
});
}
var img = new Image();
$(img).load(function(){
$('.container').append($(this));
}).attr({
src: someRemoteImage
}).error(function(){
//do something if image cannot load
});
После того, как вы получите путь к изображению, попробуйте любой из следующих способов
(так как вам нужно установить больше атрибута, чем просто src), создайте HTML и замените его на целевой регион
$('#target_div').html('<img src="'+ imgPaht +'" width=100 height=100 alt="Hello Image" />');
вам может потребоваться добавить некоторую задержку при изменении атрибута "SRC"
setTimeout(function(){///this function fire after 1ms delay $('#target_img_tag_id').attr('src',imgPaht); }, 1);
Я представляю, что вы определяете свое изображение примерно так:
<img id="image_portrait" src="" alt="chef etat" width="120" height="135" />
Вы можете просто загрузить / обновить изображение для этого тега и установить / изменить значения (ширина, высота):
var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);
В jQuery 3.x используйте что-то вроде:
$('<img src="'+ imgPath +'">').on('load', function() {
$(this).width(some).height(some).appendTo('#some_target');
});