我需要在以下条件下为图像触发事件:
1)图像已加载(以下功能负责处理) 2)显示图像。 (如果图像尚未显示,则height()和width()返回零,这意味着我无法调整图像大小。
这里的主要问题是我的图像已加载到隐藏div的子项中。由于它是隐藏div的子元素,因此change()将不起作用。
以下是我目前使用的功能:
//Takes the number of pixesl to resize the x-axis of the image to
$.fn.resizeImage = function(newX) {
return this.each(function() {
$this = $(this);
//The load event is defined via plugin and takes care of the problem of the load event
//not firing for elements that have been cached by the browser.
$this.bind('load', function(){
var y = $this.height();
var x = $this.width();
//return if image does not for some reason
if(x == 0 || y == 0){return;}
//alert('y: ' + y + ' x: ' + x);
var ratio = y / x;
var newY = Math.floor(newX * ratio);
$this.height(newY);
$this.width(newX);
});
});
};
答案 0 :(得分:0)
<img>
个元素具有 height 和 width 属性,这些属性在确定图像的尺寸时由浏览器自动填充。 .height()
和.width()
映射到隐藏元素时返回0的更通用的 offsetHeight 和 offsetWidth 属性。直接访问 height 和 width 属性应该可以使代码正常工作:
//Takes the number of pixesl to resize the x-axis of the image to
$.fn.resizeImage = function(newX) {
return this.each(function() {
var $this = $(this);
//The load event is defined via plugin and takes care of the problem of the load event
//not firing for elements that have been cached by the browser.
$this.bind('load', function() {
var y = this.height;
var x = this.width;
//return if image does not for some reason
if (x == 0 || y == 0) {
return;
}
//alert('y: ' + y + ' x: ' + x);
var ratio = y / x;
var newY = Math.floor(newX * ratio);
$this.height(newY);
$this.width(newX);
});
});
};