简体   繁体   English

首次加载页面时脚本不起作用

[英]Script doesn't work when page is loaded first time

I have a problem with my js script to set height of images on my page. 我的js脚本在设置页面上图像的高度时遇到问题。

It looks like this: 看起来像这样:

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);
            });
        }

When I go to page first time, images gets height:0px; 当我第一次进入页面时,图像的height:0px; , but when I reload page images gets height calculated from script. ,但是当我重新加载页面图像时,高度是根据脚本计算得出的。

It's happening when user come first time. 用户第一次来的时候就发生了。 When I use chrome incognito window, the problem exist, so it's happening only first time, after reload everything is fine. 当我使用chrome隐身窗口时,问题就存在了,所以这只是第一次,重新加载后一切都很好。

Many thanks for solutions. 非常感谢您的解决方案。

Make sure the page is completely loaded, before executing the script 执行脚本之前,请确保页面已完全加载

do this by warping your code into the ready function 通过将代码扭曲到ready函数中来做到这一点

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

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

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