zoukankan      html  css  js  c++  java
  • window.onload

     前端页面加载是从上往下,从左往右的顺序进行的,如果需要在整个页面加载完成之后再执行需要被执行的js代码,就可以使用window.onload了;

    1.看下面一段代码,这段代码在执行的时候是有问题的

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #box{
                 100px;
                height: 100px;
                background: #f00;
            }
        </style>
        <script>
           // alert(document.getElementById('btn'));  //null,表示取到的对象为空
                    document.getElementById('btn').onclick = function(){
                    document.getElementById('box').style.width = '200px';
                    document.getElementById('box').style.height = '200px';
        };
    </script>
    </head>
    <body>
    <input type="button" name="btn" id="btn" value="按钮" />
    <div id="box"></div>
    </body>
    </html>
    

    原因: 页面中的代码一般会从上到下,从左到右的顺序执行;当代码走到18行的时候,会从页面中的id为btn的元素,,但是下面的代码还没有执行,所以他找不到,这样的话就会报错;

    解决:window.onload = function(){当页面中的代码都加载完成之后,执行这里的代码;}

    2、正确代码如下

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #box{
                 100px;
                height: 100px;
                background: #f00;
            }
        </style>
        <script>
           // alert(document.getElementById('btn'));  //null,表示取到的对象为空
            window.onload = function(){
                    document.getElementById('btn').onclick = function(){
                    document.getElementById('box').style.width = '200px';
                    document.getElementById('box').style.height = '200px';
    
        };
            };
    </script>
    </head>
    <body>
    <input type="button" name="btn" id="btn" value="按钮" />
    <div id="box"></div>
    </body>
    </html>
    

      

  • 相关阅读:
    软件文档管理指南GB/T 16680—1996
    软件工程-产品质量
    中间件
    风险应对策略
    激励理论
    风险识别方法
    winform与js互操作
    训练报告 (2014-2015) 2014, Samara SAU ACM ICPC Quarterfinal Qualification Contest
    专题:DP杂题1
    18春季训练01-3/11 2015 ACM Amman Collegiate Programming Contest
  • 原文地址:https://www.cnblogs.com/cqq-20151202/p/6592821.html
Copyright © 2011-2022 走看看