为什么属性'naturalWidth'并不总是在JS中的背景图像上返回

Why is the attribute 'naturalWidth' not always returned on a background image in JS?

本文关键字:背景 图像 JS 返回 naturalWidth 属性 为什么      更新时间:2023-09-26

我有一个脚本,看起来像这样:

$(function(){
    var backgroundImg = document.querySelector(".image-selector");
    var bmyObject = {
        backImgNaturalWidth : backgroundImg.naturalWidth,
        /*
            Rest of the object that is okay
        */
    };
    /*Rest of my script*/
}

问题是,有时自然宽度取得正确,有时是0,这会破坏使用该数字进行计算的脚本的其余部分。任何关于为什么会发生这种情况或如何解决的想法都将非常棒。

对于那些将通过搜索这个问题的答案来寻找答案的人:您需要监听窗口加载,而不是文档就绪,因为当DOM就绪时,文档就绪将触发,而当DOM、图像等就绪时,窗口加载将触发。所以修改后的代码看起来是这样的:

$(window).load(function(){
    var backgroundImg = document.querySelector(".image-selector");
    var bmyObject = {
        backImgNaturalWidth : backgroundImg.naturalWidth,
        /*
            Rest of the object that is okay
        */
    };
    /*Rest of my script*/
});