[英]Why can't I access a property of an object in javascript?
我正在用javascript构建自己的照片库,部分出于体验,部分出于项目。 现在,我陷入了围绕对象的一些问题。
创建Image对象后,会将其推送到Gallery对象中的数组。 围绕注释// constrain to width
(要点的第55行),我试图从对象获取width
和height
属性。 如果我console.log变量img
,我可以看到对象的属性和功能。 但是,如果我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
我投票赞成关闭,但这里有一些帮助:
调用new Image
,您将重新加载它,并在load
事件触发时设置width
和height
。 那就是在其余代码运行之后-当您到达第55行时,该图像可能尚未加载。
一个简单的解决方案是直接从img.width()
获取宽度/高度,并始终在window.onload
上运行插件。 如果要支持动态加载的图像,则必须重新考虑该逻辑,并等待所有内容加载完成后再构建图库。
另外,为避免泄漏全局变量,您在$this = this
缺少var
(第7行)。
我对此不太确定:但是值得一试。 而不是“ $('#the_gallery')。css({width:this.width,height:this.height});”
也许试试这个:
“ $('#the_gallery')。css('width',this.width +'px')。css('height',this.height +'px');”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.