簡體   English   中英

jQuery調整了類准備好文檔上所有圖像的大小

[英]jQuery resize all images on document ready by class

我有一個包含圖像的頁面,我希望在使用jQuery的文檔上調整它們的大小(通過獲取某些CSS類)。 這些圖像的初始“ .test”在CSS文件中沒有任何屬性。 我知道如何給他們新的課程,以便他們可以調整大小。 但是,我想根據寬度或高度調整大小,以便它們看起來都一樣。

我的問題是我無法獲取其寬度/高度。 我的代碼是這樣的:

$(document).ready(function(){

    $('.test').each(function(){
        var img_width = $(this).width();
        var img_height = $(this).height();
        alert("My width:" + img_width + "px, My Height: " + img_height + "px");

        if (img_width > img_height)
        {
            //resize to height
        }else{
            //resize to width
        }
    });
})

我在if語句之前收到的警報始終返回0-盡管它確實顯示了正確的次數。

我還嘗試使用$(this).width;獲得寬度(以及高度) $(this).width; $(this).offsetHeight; $(this).attr('width'); 但是,如果結果不為0,則為undefined

我究竟做錯了什么?

采用

$(window).load(function() {

代替

$(document).ready(function(){

當所有圖像都實際加載后,將觸發加載事件。

使用jQuery的.load()方法將加載事件處理程序附加到窗口或圖像等更特定的項目。

資料來源: http//api.jquery.com/ready/

$(document).ready(function(){

    $('.test').load(function(){
        var img_width = $(this).width();
        var img_height = $(this).height();
        alert("My width:" + img_width + "px, My Height: " + img_height + "px");

        if (img_width > img_height)
        {
            //resize to height
        }else{
            //resize to width
        }
    });
})

您還可以簽出SLIR: https : //github.com/lencioni/SLIR

不久前,我也遇到了這個問題。 問題是圖像尚未完全加載。

但是,我建議不要這樣做。 加載大圖,然后在客戶端調整大小不是一個好方法。 您應該考慮在服務器端調整它的大小,以便用戶不必下載大圖像也不用。

您應該看看phpThumb,它是一個很棒的PHP類,可以為您調整大小並緩存圖像。 這是一個很好的工具,也是實現這一目標的更好方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM