我想在悬停时更改html类

时间:2019-02-03 20:20:13

标签: javascript jquery html

需要在悬停时更改舱位 向下倾斜

$(document).ready(function () {
    $('#home i').hover(function () {
        $(this).addClass('fas fa-angle-down');
    }, function () {
        $(this).removeClass('fas fa-angle-up');
    });
});
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#home" id="home">Services <i id="angle" class="fas fa-angle-up"></i></a>

脚本

2 个答案:

答案 0 :(得分:0)

当鼠标移到上方时,您正在添加 fa-angle-down,而当鼠标移出时,您正在移除 fa-angle-up

如果要交换它们,则需要添加一个,并删除每个类的时间。

$(document).ready(function () {
    $('#home i').hover(function () {
        $(this).addClass('fa-angle-down').removeClass('fa-angle-up');
    }, function () {
        $(this).addClass('fa-angle-up').removeClass('fa-angle-down');
    });
});

答案 1 :(得分:-1)

使用纯JavaScript,您可以仅使用Element.classList属性来切换此类,如下所示:

var x = document.getElementById("home");
x.addEventListener("mouseover", function(){
  this.children[0].classList.add("fa-angle-down");
  this.children[0].classList.remove("fa-angle-up");
})
x.addEventListener("mouseout", function(){
  this.children[0].classList.add("fa-angle-up");
  this.children[0].classList.remove("fa-angle-down");
})
.fa-angle-up:after{content:"up!";}.fa-angle-down:after{content:"down!";}
<a href="#home" id="home">Services <i id="angle" class="fas fa-angle-up"></i></a>


NB 文本仅用于说明JavaScript的工作方式。