簡體   English   中英

Javascript不首先應用,僅刷新頁面

[英]Javascript not applying first, only by refreshing page

我做了一個圖片庫,里面有肖像和風景圖片。 我使用Javascript來確定圖片是哪種模式,並根據圖片的方向應用CSS。 這是代碼:

     $(document).onload(function() {   
$('.gallery').find('img').each(function(i,elem){
var $this = $(this),
    ratio = $this.width() / $this.height();

$this.addClass((ratio < 1) ? 'portrait' : 'landscape');
});
});

第一次訪問Webist時,它不起作用,但是,一旦我刷新頁面一次,它就可以正常工作。 在新標簽頁中打開網站,該網站再次不起作用。

PS。 試圖將document.onload更改為document.ready,沒有進行任何更改。

以這種方式監聽窗口加載事件(加載圖像后將觸發):

$(window).on('load', function(e) {
    $('.gallery').find('img').each(function(i,elem){
        var $this = $(this),
        ratio = $this.width() / $this.height();
        $this.addClass((ratio < 1) ? 'portrait' : 'landscape');
    });
});

只有加載圖像后,您才能檢查其比例。

采用:

$(document).ready(init);

function init(){
// Enter your code here
}

暫無
暫無

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

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