Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 脚本不';第一次加载页面时无法工作_Javascript_Jquery - Fatal编程技术网

Javascript 脚本不';第一次加载页面时无法工作

Javascript 脚本不';第一次加载页面时无法工作,javascript,jquery,Javascript,Jquery,我的js脚本在设置页面上图像的高度时遇到问题 看起来是这样的: var $bigImages = $('.js-big-image'), $quotes = $('.js-quote'), $quoteImages = $('.js-quote-image'); if (window.innerWidth >= 460) { $bigImages.each(function (index) { var

我的js脚本在设置页面上图像的高度时遇到问题

看起来是这样的:

var $bigImages = $('.js-big-image'),
    $quotes = $('.js-quote'),
    $quoteImages = $('.js-quote-image');

        if (window.innerWidth >= 460) {
            $bigImages.each(function (index) {
                var imgHeight = $(this).height() / 2;
                $($quotes[index]).height(imgHeight);
                $($quoteImages[index]).height($quoteImages[index] / 2);
            });
        }
当我第一次进入页面时,图像得到
高度:0px,但当我重新加载页面时,图像会从脚本中计算出高度

它发生在用户第一次来的时候。当我使用chrome incognito窗口时,问题是存在的,所以它只是第一次出现,在重新加载之后,一切都很好


非常感谢您提供的解决方案。

在执行脚本之前,请确保页面已完全加载

通过将代码扭曲到函数中来实现这一点


在执行脚本之前,确保页面已完全加载

通过将代码扭曲到函数中来实现这一点


您是否在$(document).ready()中运行此代码?图像是异步加载的,因此当您检查它们的大小时,它们尚未加载,并且大小为0x0。您需要使用每个图像的“load”事件在其回调中具有实际大小,或者精确定义图像内部的宽度和高度CSS@AlanBuchanan是的,我的整个scripts.js由$(document.ready)包装(function(){//scripts here})@Robson MysterX当时所说的可能就是这里的问题,这解释了为什么它可以在后续页面加载中工作,因为浏览器将缓存图像。您可以尝试使用load事件,但它不是100%可靠的。有关更多信息,请参阅文档:参考@MysterX:您是否在$(document).ready()内运行此代码?图像异步加载,因此当您检查其大小时,它们尚未加载,并且大小为0x0。您需要使用每个图像的“load”事件在其回调中具有实际大小,或者精确定义图像内部的宽度和高度CSS@AlanBuchanan是的,我的整个scripts.js由$(document.ready)包装(function(){//scripts here})@Robson MysterX当时所说的可能就是这里的问题,这解释了为什么它可以在后续页面加载中工作,因为浏览器将缓存图像。您可以尝试使用load事件,但它不是100%可靠的。有关更多信息,请参阅文档:参考@MysterX:
$(document).ready(function () {
    var $bigImages = $('.js-big-image'),
    $quotes = $('.js-quote'),
    $quoteImages = $('.js-quote-image');

    if (window.innerWidth >= 460) {
        $bigImages.each(function (index) {
            var imgHeight = $(this).height() / 2;
            $($quotes[index]).height(imgHeight);
            $($quoteImages[index]).height($quoteImages[index] / 2);
        });
    }
});