[英]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.