简体   繁体   中英

Onload function for change style doesn't work

Well, i want that when body is completely loaded then call a function for show a hide image. I tryed a lot of things and searched a lot but anything work. I think it's pretty simple and easy but i don't know why doesn't work...I wish that anyone be able to help me.

<body onload="start()">
<div id="bg" style="display:none"></div>
</body>

function start() {
document.getElementById("bg").style.display = 'block';
}

Here Jsfiddle link

just remove onload="start()" from your body and replace your function start for

<script>
    window.onload=function() {
        document.getElementById("bg").style.display = 'block';
    };
</script>

if you want use jquery, then

<script>
    $(document).ready(function (){
        $("#bg").css("display", "block");
    });
</script>

That's because you need to run your Javascript inside the body tag. Actually at the end. Conversely, the start function will be undefined and nothing happens:

<body onload="start()">
    <div id="bg" style="display:none"></div>
    <script>
        function start() {
            document.getElementById("bg").style.display = 'block';
        }
    </script>
</body>

you have to option:

1- add script at before starting

<script type="text/javascript">
    $(document).ready(function () {
        //Add your code here to run after fully page load
        document.getElementById("bg").style.display = 'block';
    });
</script>

2- or add your script at end of <body> before ending </body> tag:

<script type="text/javascript">
     //Add your code here to run after fully page load
     document.getElementById("bg").style.display = 'block';
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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