我在点击链接后使用Ajax功能接收图像,所以我不知道它们的宽度..我想要更改图像的css,如果它们大于650像素。所有图像都具有相同的类名.popup_pics
所以我做了:
$(document).ready(function (e) {
$('a[class*="popup"]').click(function(){
showPics(current); //Ajax call
if ($(".popup_pics").clientWidth > 649) {
alert($("img.popup_pics").width());
}
else {
alert($("img.popup_pics").width());
}
}
}
但它给了我undefined
所以我认为那是因为图像尚未加载。
我怎样才能做到这一点 ?
谢谢
答案 0 :(得分:1)
等待图像加载,然后获取其宽度。这样的事情应该有效:
$("img.popup_pics").each(function() {
var img = $(this),
src = img.attr('src'),
image = new Image();
image.onload = function() {
// detect width here
alert(img.width());
};
image.src = src;
});
只有在AJAX成功返回并更改了HTML后,才会忘记执行此代码。
答案 1 :(得分:0)
.width(http://api.jquery.com/width/)和.height(http://api.jquery.com/height/)不是属性而是jquery函数,所以这段代码可以工作:
$(".popup_pics").each(function(index, domElement) {
if (domElement.clientWidth > 649) {
alert(domElement.id + ' is bigger then 649: ' + $("img.popup_pics").width());
}
else {
alert(domElement.id + ' is smaller then 649: ' + $("img.popup_pics").width());
}
});
我添加了更多代码,这里是新的小提琴:http://jsfiddle.net/nQvK3/4/
// - 更新代码
$(document).ready(function() {
/*
var request = $.ajax({
url: "images.php?gallery_id=1",
type: "GET",
data: {id : menuId},
dataType: "json"
});
request.done(function(ajaxImagesResultObject) {*/
// this is what ajax returns to you, probably an array of objects
// to test it in your code uncomment the ajax call and comment out the following object
var ajaxImagesResultObject = { imagesArray:
[
{
name: 'stackoverflow small',
url: 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png'
},
{
name: 'stackoverflow big',
url: 'http://cdn.sstatic.net/stackexchange/img/logos/careers/careers-logo.png'
}
]
};
console.log(ajaxImagesResultObject);
showPics(ajaxImagesResultObject);
/*});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
*/
});
var showPics = function(ajaxImagesResultObject) {
// foreach image that is contained in the result array
$.each(ajaxImagesResultObject.imagesArray, function(index, imageData) {
var imageElement = $('<img src="' + imageData.url + '" id="' + index+1 + '" title="' + imageData.name + '" />');
// now we add (append) the image inside of the imagesBox element
$('#imagesBox').append(imageElement);
// now we check its width and if it is bigger then 649 we add a resize class
// to save bandwidth images that are too big should get resized on the server not the client
if ($('#' + index+1).width() > 649) {
$('#' + index+1).addClass('imageResizer');
} else {
// do nothing
}
});
};