简体   繁体   English

window.load功能不起作用

[英]window.load function doesn't work

I got a small problem with the JavaScript window on load function. 加载功能上的JavaScript窗口出现了一个小问题。 The goal of the script is to make the height of my #headerdiv always equal to the size of the screen. 该脚本的目标是使#headerdiv的高度始终等于屏幕的大小。

When I open the page it doesn't show my #headerdiv (I guess because the height isn't added by my JavaScript code). 当我打开页面时,它没有显示我的#headerdiv (我想是因为我的JavaScript代码未添加高度)。 as soon as I resize my browser window the #headerdiv pups up and resizes to the height of the screen. 调整浏览器窗口大小后,#headerdiv便会弹出并调整到屏幕高度。 So I guess its just the window load function which doesn't work? 所以我想它只是窗口加载功能不起作用? Anyone has a suggestion? 有人有建议吗?

Here is my code: 这是我的代码:

Javascript: Javascript:

<script>
$(function(){
    $(window).load(function(){ // On load
        $('#headerdiv').css({'height':(($(window).height()))  +'px'});
    });

    $(window).resize(function(){ // On resize
        $('#headerdiv').css({'height':(($(window).height()))+ 'px'});
    });
});     
</script>

Html + css: HTML + CSS:

<style>
    #headerdiv {width:100%; background:blue;padding:0;margin:0;overflow:auto;}​
</style>

<div id="headerdiv"></div>

You don't need there $( window ).load() as $(function(){ already do $( document ).ready() (see official docs for shortcuts) 您不需要那里的$( window ).load()作为$(function(){已经完成$( document ).ready() (有关快捷方式,请参见官方文档

So at this point your code already loaded. 因此,此时您的代码已经加载。 Just try: 你试一试:

$(function(){

   $('#headerdiv').css({'height':(($(window).height()))  +'px'});

   $(window).resize(function(){ // On resize
    $('#headerdiv').css({'height':(($(window).height()))+ 'px'});
   });

});

Depending on whether you need to wait for all images to load, use either: 根据是否需要等待所有图像加载,使用以下任一方法:

$(window).load(function(){ // On load
  $('#headerdiv').css({'height':(($(window).height()))  +'px'});
});

$(function(){
   $(window).resize(function(){ // On resize
      $('#headerdiv').css({'height':(($(window).height()))+ 'px'});
   });
});

or the answer given by @antyrat. 或@antyrat给出的答案。 You shouldn't wrap the $(window).load in a $(function() 您不应该将$(window).load包装在$(function()

I would expand on antyrat's answer like so: 我会像下面这样扩展antyrat的答案
(there is no need to repeat code): (无需重复代码):

$(function(){

   $(window).resize(function(){ // On resize
       $('#headerdiv').css({'height':  $(window).height() + 'px'});
   }).trigger('resize'); //do the resize function on start

});

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

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