【问题标题】:Script doesn't work when page is loaded first time第一次加载页面时脚本不起作用
【发布时间】:2018-01-09 10:40:24
【问题描述】:

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

当我第一次进入页面时,图像会得到height:0px;,但是当我重新加载页面时,图像会得到从脚本计算的高度。

当用户第一次来时就会发生这种情况。当我使用chrome隐身窗口时,问题存在,所以它只是第一次发生,重新加载后一切都很好。

非常感谢您的解决方案。

【问题讨论】:

  • 您是否在 $(document).ready() 中运行此代码?
  • 图片是异步加载的,所以当你检查它们的大小时,它们还没有加载,大小为 0x0。您需要使用每个图像的“加载”事件在其回调中具有实际大小,或者在 CSS 中准确定义宽度和高度
  • @AlanBuchanan 是的,我的整个 scripts.js 都被 $(document).ready(function(){ //scripts are here });
  • @Robson MysterX 当时所说的可能是这里的问题,这解释了为什么它可以在后续页面加载时工作,因为浏览器将缓存图像。您可以尝试使用 load 事件,但它不是 100% 可靠的。有关更多信息,请参阅文档:api.jquery.com/load-event

标签: javascript jquery


【解决方案1】:

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

通过将您的代码扭曲到 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);
        });
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多