mute/unmute 图标 js fontawesome

mute/unmute icon js fontawesome

我的函数应该将图标更改为静音或取消静音,但它有时会说 class 未定义。不知道为什么。

var i = document.getElementById("sound")
var unmute = false

function change() {
  console.log(i.className)
  if (unmute == false) {
    i.className = "fas fa-volume volumen"
    console.log("unmute")
    unmute = true;
  } else {
    i.className = "fas fa-volume-mute volumen"
    console.log("mute")
    unmute = false
  }

}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<strike>
    <i id="sound" onclick="change()" class="fas fa-volume-mute volumen"></i>
<strike>

尝试将 i 的声明放在函数中。

var unmute = false;

function change() {
    let i = document.getElementById("sound");
    console.log(i.className)

    if (unmute == false) {
        i.className = "fal fa-volume volumen";
        console.log("unmute");
        unmute = true;
    } else {
        i.className = "fal fa-volume-mute volumen";
        console.log("mute");
        unmute = false;
    }
}

你打算在其他函数中使用变量unmute吗?如果没有,您可以尝试这样做:

function change() {
    let i = document.getElementById("sound");
    let current_class = i.className;
    
    current_class = current_class == "fal fa-volume-mute volumen" ? "fal fa-volume volumen" : "fal fa-volume-mute volumen";
}

您还可以使用 jQuery 在 class 个名称之间切换:

$("#sound").on('click', function(){
    $("#sound", this)
         .toggleClass("fal fa-volume volumen")
         .toggleClass("fal fa-volume-mute volumen");
});

这没有任何意义,但它对我有用我将 var i(现在称为声音)声明为函数内部的本地变量,现在它起作用了

var unmute = false
function change(){
let sound = document.getElementById("sound")
console.log(sound.className);
if(unmute == false){
sound.className ="fal fa-volume volumen"
console.log("unmute")
unmute = true;
     }
else{
      sound.className ="fal fa-volume-mute volumen"
      console.log("mute")
      unmute = false
    }

    }