Safari,Chrome在页面加载之前在window.load中运行代码

Safari, Chrome runs code in window.load before page loaded

本文关键字:load window 运行 代码 加载 Chrome Safari      更新时间:2023-09-26

我有一些看起来像这样的html:

 <div class="nmMap-wrapper">
        <div id="draggable" class="nmMap-image">
            <div class="nmMap"></div>
        </div>
 </div>

"nmMap"我在 css 中设置了一个背景图像。

然后,

我有一个javascript加载背景图像,将其追加为图像,然后获取宽度和高度,并提醒所有不同的变量。

脚本如下所示:

jQuery(window).load(function($) {
sceneConstructor();
});
function sceneConstructor() {
    var bgHeight;
    var bgWidth;
    var bgAspectRatio;
    function init() {
        getBgSize();
        alertRatio();
    }
    function getBgSize() {
        var bgsrc = jQuery('.nmMap').css('background-image')
            .replace('url("', '')
            .replace('url(', '')
            .replace('")', '')
            .replace(')', '')
            .replace('"', '')
            .replace("'", '');
        var bgImg = jQuery('<img />');
        //bgImg.hide();
        jQuery('.nmMap').append(bgImg);
        bgImg.attr('src', bgsrc);
        bgImg.bind('load', function() {
            var width = jQuery(this).width();
            var height = jQuery(this).height();
            alert('first height' + height);
            setAspectRatio(width, height);
        });
    }
    function setAspectRatio(width, height) {
        alert('second height: ' + height);
        bgHeight = height;
        bgWidth = width;
        bgAspectRatio = bgWidth / bgHeight;
        alert('trejde: ' + bgHeight);
        jQuery('.nmMap').addClass('ration');
    }
    function alertRatio() {
        alert('bgheight ' + bgHeight);
        alert('bgwidth ' + bgWidth);
        alert('bgheight ' + bgHeight);
        alert('bgaspect ' + bgAspectRatio);
    }
    init();
}

所有这些都在 Firefox 中工作,除了 alertRatio() 中的第一个警报总是未定义。但是在 safari、chrome 和 IE 中,就像首先运行alertRaiom()一样,因此所有警报都是未定义的。

有人可以帮忙告诉我发生了什么事吗?

尝试使用jquery的默认.ready。

此代码在加载 DOM 后加载。

jQuery( document ).ready(function() {
sceneConstructor();
}):

你也可以

jQuery( window ).ready(function() {
sceneConstructor();
}):

来源: https://api.jquery.com/ready/

如果在

设置图像的src属性之前bind()事件侦听器是否有帮助?