Html 如何仅使用 javascript 切换/切换 div onclick 的类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19075104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:55:18  来源:igfitidea点击:

How to toggle/switch class of a div onclick using only javascript

javascripthtmlclassonclicktoggle

提问by Umesh Meena

I want a divto switch its class (toggle) onclick and then revert back to original class onclick again

我想要一个div切换它的类(切换)onclick,然后再次恢复到原来的类 onclick

My code is:

我的代码是:

 function myfunc() {
    //the code over here
 }
.normal { 
  width:25%;
  height:25%;
  background: #f00;
}

.active { 
  width:100%;
  height:100%;
  background: #f00;
}

#div{}
<body>
  <div id="div" onclick="myfunc()">click here</div>
</body>

回答by Nishad K Ahamed

using pure js:

使用纯js:

<div id="div" class="normal" onclick="myfunc(this)">click here</div>

js

js

function myfunc(div) {
  var className = div.getAttribute("class");
  if(className=="normal") {
    div.className = "active";
  }
  else{
    div.className = "normal";
  }
}

回答by Ben

Use:

用:

// hasClass
function hasClass(elem, className) {
 return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
}
// toggleClass
function toggleClass(elem, className) {
 var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, " " ) + ' ';
    if (hasClass(elem, className)) {
        while (newClass.indexOf(" " + className + " ") >= 0 ) {
            newClass = newClass.replace( " " + className + " " , " " );
        }
        elem.className = newClass.replace(/^\s+|\s+$/g, '');
    } else {
        elem.className += ' ' + className;
    }
}
document.getElementById('div').onclick = function() {
    toggleClass(this, 'active');
}
div {
    margin:20px;
    padding:10px 15px;
    background:#FFD202;
    border-radius:5px;
    color:#222;
    display:inline-block;
    text-decoration:none;
}
.active {
    background:#000;
    color:#FFD202;
}
<div id="div" href="#">Click a few times, toggle me!</div>

回答by Tiberiuscan

I've been looking for a solution myself where I want to toggle between two images with pure JavaScript. I think this is quite an effective method of using JavaScript. (I had to switch between a plus and a minus image sign on user click.)

我自己一直在寻找一个解决方案,我想用纯 JavaScript 在两个图像之间切换。我认为这是使用 JavaScript 的一种非常有效的方法。(我必须在用户单击时在加号和减号图像符号之间切换。)

HTML

HTML

<a href="#" class="plus" onclick="toggleClass(this,'minus')">Text here</a>

CSS

CSS

.plus {
  background-image: url(../img/plus-circle-grey.svg);
}

.minus {
  background-image: url(../img/minus-circle-grey.svg);
}

JavaScript

JavaScript

function toggleClass(e,c) {
    (e).classList.toggle(c);
}

Works like a charm.

奇迹般有效。

回答by drinxy

function myFunc(e) {
    if(e.className == 'active') {
        e.className = 'normal';
    } else {
        e.className = 'active';
    }
}

then have:

然后有:

<div id="div" onclick="myFunc(this)">blah</div>

pretty sure that is answered in a number of other questions round here too.

很确定这也在此处的许多其他问题中得到了回答。

回答by David says reinstate Monica

Move away from obtrusive JavaScript, bind the event-handlers in the JavaScript of the page, not in the HTML (this makes for easier future maintenance):

远离干扰性的 JavaScript,在页面的 JavaScript 中绑定事件处理程序,而不是在 HTML 中(这使得将来的维护更容易):

function classToggle() {
    this.classList.toggle('class1');
    this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);

JS Fiddle demo.

JS小提琴演示

回答by Sudhir Bastakoti

do:

做:

function myfunc(){
  var divEle = document.getElementById("div"),
      current_class = divEle.className;
  divEle.className = (current_class == "active") ? "normal" : "active";
}

回答by swordkorn

A good way to approach your dilemma is using the classList API. I switch classes using nested for loops (for repeating instances of a class) and query the document like so:

解决您的困境的一个好方法是使用 classList API。我使用嵌套的 for 循环切换类(用于重复类的实例)并像这样查询文档:

var desiredElement = document.querySelectorAll('.light');

function switchTheme() {
    for (var i = 0; i < desiredElement.length; i++) {
        if (desiredElement[i].classList.contains('light')) {
            desiredElement[i].classList.remove('light');
            desiredElement[i].classList.add('dark');
        } else if (desiredElement[i].classList.contains('dark')) {
            desiredElement[i].classList.remove('dark');
            desiredElement[i].classList.add('light');
        }
    }
}

By adding a button or hyperlink to either perform this function onclick or as href, I can toggle any element in the HTML document containing the light or dark class and effectively make a toggle switch to switch the sub design classes.

通过添加按钮或超链接来执行此功能 onclick 或作为 href,我可以切换 HTML 文档中包含亮类或暗类的任何元素,并有效地进行切换以切换子设计类。

I used this to create a dark theme for a website that can toggle to a lighter theme by the user if desired.

我用它为网站创建了一个深色主题,如果需要,可以由用户切换到较浅的主题。

var desiredElement = document.querySelectorAll('.light');

function switchTheme() {
  for (var i = 0; i < desiredElement.length; i++) {
    if (desiredElement[i].classList.contains('light')) {
      desiredElement[i].classList.remove('light');
      desiredElement[i].classList.add('dark');
    } else if (desiredElement[i].classList.contains('dark')) {
      desiredElement[i].classList.remove('dark');
      desiredElement[i].classList.add('light');
    }
  }
}
.light {
  background-color: #ddd;
}

.dark {
  background-color: #333;
}
<DOCTYPE HTML>
<html>
  <body class="light">
    <button onclick="switchTheme()">Toggle</button>
  </body>
</html>

回答by Felix Eve

There are already quite a few answers but I think this is the simplest / most succinct approach here:

已经有很多答案,但我认为这是最简单/最简洁的方法:

<div onclick="$(this).toggleClass("active")">click here</div>

回答by A-Sharabiani

If you want to switch/swap class-Aand class-B, toggle both classes:

如果你想切换/交换class-Aclass-B,切换两个类:

function myFunc(element) {
    element.classList.toggle("class-A");
    element.classList.toggle("class-B");
}

And

<div onclick="myFunc(this)" />

回答by Ronjon

Try it with jquery may this help

用 jquery 试试这可能有帮助

html-

html-

<div id="div1" class="normal">click here</div>
<div id="div2" class="normal">click here</div>

css-

css-

.normal{ width:25%;height:25%;background: #f00;}
.active{ width:100%;height:100%;background: #f00;}

jquery-

jquery-

$(document).ready(function(){
                $(".normal").click(function(){
                    var thisobj =  $(this);
                    if(thisobj.hasClass("active"))
                    {
                        $(this).removeClass("active");
                    }else
                    {
                        $(this).addClass("active");
                    }
                });
            });

jsfiddle

提琴手