Javascript 中的 classList.toggle

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25463653/
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-10-28 04:32:46  来源:igfitidea点击:

classList.toggle in Javascript

javascriptclasstogglecontains

提问by Jaros?aw Rewers


I'm trying to assign .hidden to certain elemement when class is not present and remove class .hidden if this class is already assigned to this element. In other words - I just want to toggle class.


当 class 不存在时,我试图将 .hidden 分配给某些元素,如果该类已分配给该元素,则删除 class .hidden 。换句话说 - 我只想切换课程。

I wrote code

我写了代码

var isHidden = document.getElementById("inputSelected").classList.toggle("hidden");

but it doesn't work. But when I console log classList.contains

但它不起作用。但是当我控制台日志 classList.contains

var isHidden = document.getElementById("inputSelected").classList.contains("hidden");

it returns false - which means, that this class it not assigned. So why it doesn't toggle?

它返回 false - 这意味着它没有分配这个类。那么为什么它不切换?

More code:

更多代码:

<!DOCTYPE html>
<html>
<head>
<title>Kalkulator dat</title>
<meta name="description" content="Kalkulator dat. Ile dni min??o od wskazanej daty? Jaka b?dzie data za dan? ilo?? dni?">
<link rel="StyleSheet" type="text/css" href="style.css">
</head>

<body>
<h1>Kalkulator dat</h1>
<div id="daysPassed">
    <h2>Ile pe?nych dni min??o?</h2>
    <form id=daysPassedForm">
        <label for="firstDateDP">Data pocz?tkowa:</label>
        <input type="date" id="firstDate">
        <fieldset>
            <input type="radio" id="toToday" name="todayOrSelected">    
            <label for="toToday">Do dzi?</label>

            <input type="radio" id="toSelected" name="todayOrSelected"> 
            <label for="toSelected">Do wskazanej daty</label> 
            <p id="inputSelected">(<input type="date" id="selectedEndDate">)</p>

        </fieldset>
        <input type="submit" value="Oblicz">
        </form>
</div>

<div id="daysPassedResult" class="result">
    <p id="daysPassedInfo">Od wskazanej daty min??o x dni</p>
</div>

<div id="dateIndicate">
    <h2>Jaka b?dzie data?</h2>
    <form id="dateIndicateForm">
        <ul>
            <li>
                <label for="firstDateDI"><span>Data pocz?tkowa:</span></label>
                <input type="date" id="firstDateDI">
            </li>

            <li>
            <label for="numberOfDays"><span>Liczba pe?nych dni:</span></label>
            <input type="number" id="numberOfDays" step="1">
            </li>

            <li>
            <input type="submit" value="Oblicz">
            </li>
        </ul>
    </form>
</div>

<div id="dateIndicateResult" class="result">
    <p id="dateIndicateResult">Po x dniach od y b?dzie</p>
</div>

<script src="script.js"></script>
</body>
</html>


div {
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box; 
margin-bottom: 7px;
}

body {
margin: 0 auto;
width: 40%;
background-color: #FFCA51;
}

div {
padding: 5px;
border-radius: 15px;
}

p {
margin: 8px 0 8px 0;
}

ul {
list-style-type: none;
padding: 0;
}

h1 {
text-align: center;}

fieldset {
border: none;
}

input {
margin: 2px;
padding: 1px;
}

span {
width: 115px;
text-align: right;
display: inline-block;
}


#daysPassed {
background-color: #E8A849;
padding-left: 16px;
}

#inputSelected {
margin: 0 0 0 8px;
display: inline-block;
}

#daysPassedResult {
background-color: #FFA75D;
}

#dateIndicate {
background-color: #E87A49;
padding-left: 16px;
margin-top: 20px;
}

#dateIndicateResult {
background-color: #FF6D51;
}

.result {
margin: 8px 0 8px 16px;
padding-left: 12px;
max-width: 50%;
}

.hidden {
display: none;}


function preparePage() {
    document.getElementById("inputSelected").classList.toggle("hidden");
    document.getElementById("daysPassedResult").classList.toggle("hidden");
    document.getElementById("dateIndicateResult").classList.toggle("hidden");
}

window.onload = function() {
    preparePage();
};

Right now second and third line of preparePage works, but first (#inputselected) doesn't

现在准备页面的第二行和第三行有效,但第一行(#inputselected)无效

采纳答案by and.coffee.code

DOMTokenListReference from Mozilla:

来自 Mozilla 的DOMTokenList参考:

toggle ( token )- removes tokenfrom string and returns false. If tokendoesn't exist it's added and the function returns true

toggle ( token )-token从字符串中删除并返回 false。如果token不存在,则添加它并且该函数返回true

Your code actually works, but it seems that the issue is not caused by the DOMTokenList .toggle()function, but by a CSS id #inputSelected:

您的代码实际上有效,但问题似乎不是由 DOMTokenList.toggle()函数引起的,而是由 CSS id 引起的#inputSelected

#inputSelected {
  margin: 0 0 0 8px;
  display: inline-block; /* will never let .hidden to actually set the "display: none". */
}

.hidden {
  display: none;
}

A simple way to fix it is to define:

修复它的一个简单方法是定义:

.hidden {
  display: none !important;
}

or define display: inline-block;in a separate class.

display: inline-block;在单独的类中定义。

If the problem really is the .toggle, DOMTokenListstill has:

如果问题确实是.toggleDOMTokenList仍然有:

  • .contains
  • .add
  • .remove
  • .contains
  • .add
  • .remove

Otherwise, you can use jQuery or manage the element.classNameby hand.

否则,您可以使用 jQuery 或element.className手动管理。