【问题标题】:Javascript code only working after page refresh and not first viewing [duplicate]Javascript代码仅在页面刷新后才有效,而不是第一次查看[重复]
【发布时间】:2014-02-19 23:34:28
【问题描述】:

我正在使用一些 javascript 来检查我所有的图像的宽度并根据需要添加一个类。

看起来像这样:

$(document).ready(function(){
// check each image in the .blogtest divs for their width. If its less than X make it full size, if not its poor and keep it normal
var box = $(".blogtest");
box.find("img.buildimage").each(function() {
   var img = $(this), width = img.width();
   if (width >= 700) {
      img.addClass("buildimage-large");
   } else if (width < 700) {
      img.addClass("buildimage-small");
   }
}); 
});

问题是,当您第一次访问页面时,图像没有添加类,而是仅在您刷新页面时才起作用。

有什么解决办法吗?

【问题讨论】:

  • @zer02 媒体查询对图像宽度没有帮助

标签: javascript jquery css image


【解决方案1】:

您需要使用加载处理程序,因为当触发就绪处理程序时,可能不会加载图像,因此第一次宽度将为 0,第二次图像可能会缓存在浏览器中,从而加快加载速度,因此当触发就绪处理程序时,图像可能已经加载,所以它正在工作

$(document).ready(function () {
    // check each image in the .blogtest divs for their width. If its less than X make it full size, if not its poor and keep it normal
    var box = $(".blogtest");
    box.find("img.buildimage").on('load', function () {
        var img = $(this),
            width = img.width();
        if (width >= 700) {
            img.addClass("buildimage-large");
        } else if (width < 700) {
            img.addClass("buildimage-small");
        }
    }).filter(function () {
        //if the image is already loaded manually trigger the event
        return this.complete;
    }).trigger('load');
});

但要记住的另一点是,如果图像已经加载,则在触发就绪处理程序时,注册的 load 处理程序将不会被触发,因此在注册事件处理程序后,我们需要过滤掉已经加载的图片,然后手动触发加载事件,这样对于这些图片,加载事件就会被触发

【讨论】:

    【解决方案2】:

    jQuery 的 .ready 处理程序不会等待加载样式表或图像等外部内容:

    如果代码依赖于加载的资源(例如,如果需要图像的尺寸),则应将代码放在加载事件的处理程序中。

    jQuery 中的加载事件处理程序如下所示:

    $(document).on('load', function() {
        // Your code here
    });
    

    它在页面刷新时起作用的原因可能是由于浏览器缓存了图像(因此它们在浏览器完成 HTML 解析之前就准备好了。

    【讨论】:

      猜你喜欢
      • 2017-05-13
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 2014-11-16
      • 2014-05-14
      • 2019-03-04
      相关资源
      最近更新 更多