【问题标题】:Javascript not applying first, only by refreshing pageJavascript不首先应用,仅通过刷新页面
【发布时间】:2018-04-15 11:14:26
【问题描述】:

我制作了一个图片库,其中有肖像和风景图片。 我使用 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');
});
});

它不起作用,首先访问网站时,尽管我刷新一次页面后它就可以完美运行。在新标签页中打开网站,它再次无法正常工作。

PS。尝试将 document.onload 更改为 document.ready,但没有更改任何内容。

【问题讨论】:

  • 如果您认为问题可能与首先运行的函数有关,您是否检查过该函数是否确实在第一个页面加载时运行?

标签: javascript jquery html image


【解决方案1】:

以这种方式监听窗口加载事件(加载图像后会触发):

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

只有在图像加载后,您才能检查它们的比例。

【讨论】:

    【解决方案2】:

    用途:

    $(document).ready(init);
    
    function init(){
    // Enter your code here
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-25
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      相关资源
      最近更新 更多