无法让 CSS 通过 Javascript 更改类

Can't get CSS to change class through Javascript

本文关键字:Javascript 通过 CSS      更新时间:2023-09-26

我正在尝试学习Web开发,但我坚持通过Javascript更改CSS类。我看过其他网站和问题,但没有一个对我有用,所以我一定在做一些我不知道的愚蠢事情。

我试图让它做的是当我悬停在上面时从高度 50 扩展到 200。但是,它不执行任何操作。

(我知道我可以做一个:hover,但我需要它在Javascript中以满足其他需求)

.CSS:

.box{
    width: 300px;
    height: 50px;
    -webkit-transition: height 2s ease;
    -moz-transition: height 2s ease;
    -o-transition: height 2s ease;
    transition: height 2s ease;
}
.box-expand{
    height: 200px;
}

.HTML:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="../css/about.css">
    <script src="../javascript/preview_control.js"></script>
</head>
<body>
    <div class="box">
</body>

Javascript:

var box = document.getElementsByClassName("box")[0];
box.onmouseover = function() {  
    box.toggleClass("box-expand");
}
我认为

你已经很接近了。 toggleClass()是一个jQuery函数,classList.toggle是用于vanilla JavaScript的。

box.onmouseover = function() {  
  box.classList.toggle("box-expand");
}

hackNightly 的答案在这里效果很好......我添加了缺少的结束标签...

var box = document.getElementsByClassName("box")[0];
box.onmouseover = function() {
  box.classList.toggle("box-expand");
}
.box {
  background-color:green;
  width: 300px;
  height: 50px;
  -webkit-transition: height 2s ease;
  -moz-transition: height 2s ease;
  -o-transition: height 2s ease;
  transition: height 2s ease;
}
.box-expand {
  height: 200px;
}
<html>
<head>
  <link rel="stylesheet" type="text/css" href="../css/about.css">
  <script src="../javascript/preview_control.js"></script>
</head>
<body>
  <div class="box"></div>
</body>
</html>

我用hackNightly的答案修复了它,我的盒子类似乎用50px覆盖了高度。删除它修复了它。