最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

change css onload with javascript - Stack Overflow

programmeradmin5浏览0评论

It's a simple javascript mand to get the classname to change when the page loads. What am I doing wrong that it isn't working? /

<html>
 <head>
 <style>
   .away {
        margin: 30px 0 0 0 !important;
        position:fixed;
        -webkit-transition: margin 0.6s;
        -moz-transition: margin 0.6s;
        -o-transition: margin 0.6s; 
   }
   .in {
        margin:0;
        position:absolute;
   }

 </style>
 <script>
     window.onload = function pre-loader() {
        document.getElementByClassName('away').className = 'in';
     };
 </script>
</head>

<div class="away">
this should slide up when the page loads
</div>

It's a simple javascript mand to get the classname to change when the page loads. What am I doing wrong that it isn't working? http://jsfiddle/wtH2Y/4/

<html>
 <head>
 <style>
   .away {
        margin: 30px 0 0 0 !important;
        position:fixed;
        -webkit-transition: margin 0.6s;
        -moz-transition: margin 0.6s;
        -o-transition: margin 0.6s; 
   }
   .in {
        margin:0;
        position:absolute;
   }

 </style>
 <script>
     window.onload = function pre-loader() {
        document.getElementByClassName('away').className = 'in';
     };
 </script>
</head>

<div class="away">
this should slide up when the page loads
</div>
Share Improve this question asked Jul 17, 2013 at 1:37 stevenspielstevenspiel 6,01914 gold badges63 silver badges90 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

A few things:

  • Function names cannot have dashes in them. Rename your function.
  • If you're using a named function, I wouldn't assign it to a property this way. Either make it anonymous or assign it like so:

    function foo() {
        ...
    }
    
    window.onload = foo;
    

    Otherwise, you won't be able to call foo().

  • getElementByClassName should be getElementsByClassName (notice the s). Also, since it'll return a collection of elements, you will need to iterate over it with a for loop.

Because the function is document.getElementsByClassName and not document.getElementByClassName. It returns an Array. So you need to get the first element and apply the class. Like this...

document.getElementsByClassName('away')[0].className = 'in';

To make it simple, why don't you assign an id to the div

<div class="away" id="mydiv">

and then use document.getElementById. Like this...

document.getElementById('mydiv').className = 'in';

It is much simpler and easy to use.

发布评论

评论列表(0)

  1. 暂无评论