[英]jquery fire event when element is shown
我需要在以下條件下為圖像觸發事件:
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);
});
});
};
<img>
元素具有height和width屬性,當瀏覽器確定圖像尺寸時,它們會自動填充。 .height()
和.width()
映射到更通用的offsetHeight和offsetWidth屬性, 這些屬性在隱藏元素時返回0。 直接訪問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);
});
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.