我正在用 javascript 构建自己的照片库,部分是为了体验,部分是为了一个项目。现在,我遇到了一些关于对象的问题。
创建 Image 对象时,会将其推送到 Gallery 对象中的数组。围绕评论// constrain to width
(要点中的第 55 行),我试图从对象中获取width
andheight
属性。如果我 console.log 变量img
,我可以看到对象的属性和功能。但是,如果 I console.log(img.height);
,我会变得不确定。我究竟做错了什么?
整个文件如下。它也是为了更容易阅读的要点。
var Image = function(img, gallery){
// init with an image in jquery form
this.src = img.attr('src');
this.setDimensions = function(){
var temp_height, temp_width;
$this = this;
$this.image = $('<img />').attr('src', this.src).load(function(){
$this.height = this.height;
$this.width = this.width;
});
};
// init functions
this.setDimensions();
gallery.images.push(this);
}; // Image
var Gallery = function(){
this.width = $(window).width();
this.height = $(window).height();
this.images = [];
this.createElements = function(){
$('body').append('<div id="the_gallery"></div>');
$('#the_gallery').css({width: this.width, height: this.height});
};
this.open = function(){
this.createElements();
var img = this.images[0];
// see if the image is bigger than the window
if( this.width >= img.width && this.height >= img.height) {
console.log('image < window');
// just show the image, centered
}
else {
console.log('image > window');
var temp_width, temp_height;
// constrain to height
if( img.width < img.height ) {
console.log('image width < image height');
temp_height = this.height;
temp_width = (temp_height/img.height) * img.width;
img.css({height:temp_height, width:temp_width});
}
// constrain to width
else {
console.log('image width > image height');
temp_width = this.width;
temp_height = (temp_width/img.width) * img.height;
img.image.css({height:temp_height, width:temp_width});
}
}
img.image.appendTo($('#the_gallery'));
}; // open
this.close = function(){
$('#the_gallery').remove();
}; // close
}; // Gallery
$(document).ready(function(){
$('#gallery img').click(function(){
launchGallery($(this));
}); // click
var gallery = new Gallery(),
test = new Image($('#gallery img:first'), gallery);
gallery.open();
}); // doc ready