简体   繁体   English

Javascript不首先应用,仅刷新页面

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

I have made an image gallery, in which i have portrait as well as landscape pictures. 我做了一个图片库,里面有肖像和风景图片。 I use Javascript to determine which mode the picture is, to apply css based on the pictures orientation. 我使用Javascript来确定图片是哪种模式,并根据图片的方向应用CSS。 This is the Code: 这是代码:

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

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

It does not work, when visiting the webiste first, altough it works flawlessly as soon as I refresh the page once. 第一次访问Webist时,它不起作用,但是,一旦我刷新页面一次,它就可以正常工作。 Open the website in new tab and its again not working. 在新标签页中打开网站,该网站再次不起作用。

PS. PS。 Tried to change document.onload to document.ready, didnt change anything. 试图将document.onload更改为document.ready,没有进行任何更改。

Listen to the window loaded event this way (it would fire after images are loaded): 以这种方式监听窗口加载事件(加载图像后将触发):

$(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');
    });
});

Only after images were loaded you can check their ratio. 只有加载图像后,您才能检查其比例。

Use: 采用:

$(document).ready(init);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM