为什么 CSS class 没有应用(使用 JavaScript onload)?

Why CSS class isn't applied (using JavaScript onload)?

我试图在页面加载后添加 class,因此添加的 class 中的过渡可以更改元素的高度和不透明度,但我仍然无法使其正常工作。

html 文件:

<head>
  <script>
    window.onload = function {
      document.getElementById('home-id').className='home-class';
    };
  </script>
</head>

css 文件:

#home-id {
    transition: opacity 1.5s ease-in-out 0s;
    height: 0.0em;
    opacity: 0.6;
}
html:hover #home-id {
    transition: opacity 1.5s ease-in-out 0s;
    opacity: 1;
}
.home-class {
    transition: height 1s ease-in-out 0s, opacity 1.5s ease-in-out 0s;
    height: 40em;
    opacity: 1;
}

你能告诉我我做错了什么吗,谢谢。

编辑:我只是补充说,问题不在于缺失 "()",而在于特异性。

您可以使用 classList:

// div is an object reference to a <div> element with class="foo bar"
div.classList.remove("foo");
div.classList.add("anotherclass");

// if visible is set remove it, otherwise add it
div.classList.toggle("visible");

//  add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );

alert(div.classList.contains("foo"));

div.classList.add("foo","bar"); //add multiple classes

它比使用 className 属性.

更灵活

onload 方法的函数应该是:

window.onload = function() {
  document.getElementById('home-id').className='home-class';
};

您错过了 function()

MDN:https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

为此我会使用 jQuery。在你的 HTML 文件中 link 来自 http://www.code.jquery.com 的最新版本并使用以下代码:

$(document).ready(function() { //The following block of code will be executed when the page finishes to load.
   $("#home-id").addClass("home-class"); //This line adds the class "home-class" to the element with the id "home-id"
});

如果您不熟悉 jQuery,我建议您查看 codecademy jQuery 课程。(https://www.codecademy.com/learn/jquery) jQuery 非常轻巧,使用起来极其简单并且容易学习。