调整窗口大小调整div

Duc*_*Anh 5 javascript jquery

我有这个代码

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../css/style.css" />
<style>
html,body {
    width: 100%;
    margin: 0;
    padding: 0;
}

#main {
    margin: 0 auto;
    width: 963px;
    height: 642px;
}
#preload {
    display: block;
    position: absolute;
    width: 100%;
    height: 100%;
}
.loading {
    position:absolute;
    top: 43%;
    left: 47%;
    z-index: 2;
    display: none;
}
</style>
</head>

<body>
    <div id="main">
        <img id="preload" src="preload.png"/>
        <img class="loading" src="../effects/loading icon/loading3.gif" />
    </div>
    <script type="text/javascript" src="jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="../player/player.js"></script>
    <script type="text/javascript" src="pic1.js"></script>
    <script>
    $(document).ready(function() {
        $(window).on('resize', function(){
            var maxWidth = $(window).width();
            var maxHeight = $(window).height();
            var ratio = $("#main").height() / $("#main").width();

            if(maxWidth * ratio > maxHeight) {
                $("#main").height(maxHeight);
                $("#main").width(maxHeight / ratio);
            } else {
                $("#main").width(maxWidth);
                $("#main").height(maxWidth * ratio);
            }
            $("#preload").width($("#main").width());
            $("#preload").height($("#main").height());
        }).trigger('resize');
    })(jQuery);
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我想要的是div和img里面自动调整窗口大小调整大小.问题是,在第一次页面加载时,div下面有一个空白区域,如图1所示,当我调整窗口大小时,空间消失就像你在图2中看到的那样.为什么图1中有空格,我该如何修复它,tks这么多:) 图片1

图2

更新Jsfiddle:http://jsfiddle.net/7bNjf/

小智 5

重构代码,以便image.onload最初调用resize函数.

<img id="preload" src="preload.png" onload="resizeImage()" />
Run Code Online (Sandbox Code Playgroud)

在脚本部分:

function resizeImage() {
    //calculations here...
}

window.addEventListener('resize', resizeImage, false);
Run Code Online (Sandbox Code Playgroud)

(使用vanilla JS进行说明,您需要更改的关键部分是......根据需要进行修改).

这当然意味着(?)resizeImage()也在窗口的onload/onready事件中调用.


Rok*_*jan 1

似乎是一个答案,所以我将其放在这里:

在 DOM 准备就绪时,图像仍在加载:) 将逻辑放入函数中,并在 window.resize 和 .load 中重用该函数:

jQuery(function( $ ) {


     function resizzler(){
        var $main = $('#main');
        var maxWidth = $(window).width();
        var maxHeight = $(window).height();
        var ratio = $main.height() / $main.width();

        if(maxWidth * ratio > maxHeight) {
            $main.height(maxHeight).width(maxHeight / ratio);
        } else {
            $main.width(maxWidth).height(maxWidth * ratio);
        }
        $("#preload").width($main.width()).height($main.height());
    }

    $(window).on('resize load', resizzler );

});
Run Code Online (Sandbox Code Playgroud)