简体   繁体   English

JavaScript - 更改 class 名称

[英]JavaScript - change class name

enter link description here在此处输入链接描述

In my JSFiddle - my problem is在我的 JSFiddle - 我的问题是

How I toggle and change class in the same time?如何同时切换和更改 class?

normal show "<" when click menu toggle and it show ">".

You can check if class is present in classlist and render icon accordingly您可以检查classlist是否存在于类列表中并相应地呈现图标

 function togglesidebar() { document.getElementById("mySidebar").classList.toggle('active'); const isActive = document.getElementById("mySidebar").classList.contains('active') document.getElementById("changeclass").className = `fa fa-chevron-${isActive? 'right': 'left'}`; }
 #mySidebar.active { right: 0px; width: auto; height: auto; transition: all 0.5s linear; } #mySidebar.active { right: 0px; width: auto; height: auto; transition: all 0.5s linear; } #mySidebar { position: absolute; top: 30%; right: -7%; /* width: 100px; height: 200px; */ width: 8.333333%; /* 100/1200 */ /* 100/1200 */ height: auto; opacity: 0.7; background-color: green; } #mySidebar #btn4 { top: 30%; } #btn4 { position: absolute; top: 40%; right: 95%; font-size: 100%; border-radius: 100%; padding: 10px; border: none; outline: none; background-color: green; z-index: 3; }
 <script src="https://kit.fontawesome.com/a076d05399.js"></script> <div id="mySidebar"> <button id="btn4" onclick="togglesidebar()"> <span id="changeclass" class="fa fa-chevron-left"></span> </button> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </div> </div>

Just toggle both classes to change it只需切换两个类即可更改它

function togglesidebar() {
    document.getElementById("mySidebar").classList.toggle('active')
    document.getElementById("changeclass").classList.toggle("fa-chevron-right");
    document.getElementById("changeclass").classList.toggle("fa-chevron-left");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM