使用JavaScript将类添加到可悬停元素

时间:2019-03-31 18:08:00

标签: javascript html css dom hover

我有一个按钮,它会在悬停时更改其颜色。

const btn = document.querySelector('.btn');
btn.classList.add('green-background');
.btn {
  text-decoration: none;
  background: blue;
  color: white;
  font-size: 20px;
}

.btn:hover {
  background: magenta;
  cursor: pointer;
}

.green-background {
  background: green;
}
<input class="btn" type="submit" value="Click me" />

我想将其添加到green-background类中,以便在默认状态下以及悬停时该按钮都为绿色。

3 个答案:

答案 0 :(得分:1)

您可以使用默认的,hover组合两个选择器。有关更多信息,请参见Groups of selectors on one rule

const btn = document.querySelector('.btn');
btn.classList.add('green-background');
.btn {
  text-decoration: none;
  background: blue;
  color: white;
  font-size: 20px;
}

.btn:hover {
  background: magenta;
  cursor: pointer;
}

.green-background:hover,.green-background {
  background: green;
}
<input class="btn" type="submit" value="Click me" />

答案 1 :(得分:1)

您只需要添加一个css规则即可指定悬停时.green-background的样式,您可以通过为.green-background:hover设置样式来做到这一点

const btn = document.querySelector('.btn');
btn.classList.add('green-background');
.btn {
  text-decoration: none;
  background: blue;
  color: white;
  font-size: 20px;
}

.btn:hover {
  background: magenta;
  cursor: pointer;
}

.green-background, .green-background:hover {
  background: green;
}
<input class="btn" type="submit" value="Click me" />

答案 2 :(得分:0)

 function changeclass() {
            const btn = document.querySelector('.btn');
            if (!btn.classList.contains('green-background'))
                btn.classList.add('green-background');
            else
                btn.classList.remove('green-background');

        }

<!-- language: lang-css -->

    .btn {
      text-decoration: none;
      background: blue;
      color: white;
      font-size: 20px;
    }

    .btn:hover {
      background: magenta;
      cursor: pointer;
    }

    .green-background, .green-background:hover {
      background: green;
    }

<!-- language: lang-html -->

    <input class="btn" type="submit" value="Click me" onmouseover="changeclass()" onmouseout="changeclass()" />

您询问如何通过Java脚本添加类:只需将onmouseover =“ changeclass()” onmouseout =“ changeclass()”事件添加到按钮和changeclass函数 但您也可以通过css与批准的答案相同的方式来完成此操作。