【问题标题】:Javascript How to add new class without deleting already existing ones [duplicate]Javascript如何在不删除现有类的情况下添加新类[重复]
【发布时间】:2023-03-24 06:15:02
【问题描述】:

当使用 javascript 在 html 中单击按钮时,我需要添加一个 CSS 类。但我不想删除元素已经拥有的那个。例如我有这个元素

<div class="one two"></div>

我想添加三个类所以我想要的元素到底是:

<div class="one two three"></div>

在我的现实世界问题中,我有以下代码。

HTML:

<button id="FileStatusForm:extractButton" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="submit" style="margin-right: 10px; opacity: 0.35;" onclick="disableButton(this);return false;" name="FileStatusForm:extractButton" role="button" aria-disabled="false">  

当我点击上面的按钮时,我必须添加 ui-state-disabled css 类

.ui-state-disabled{background-image: none;
opacity: 0.35;}

我想要一个带有 vanilla js 的解决方案。

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    您可以使用classList.add

    JS:

    function disableButton(x){
          x.classList.add("ui-state-disabled");
    }
    

    DEMO

    【讨论】:

      【解决方案2】:
      HTMLElementObject.className=classname
      

      W3 School Link

      【讨论】:

        【解决方案3】:
        var element = document.getElementById("your_div_id");
        element.className = "name_of_ur_class";
        

        【讨论】:

          【解决方案4】:

          因为有些人会反对 shin 链接到 w3schools 的答案。这是Mozilla开发网络链接https://developer.mozilla.org/en-US/docs/Web/API/Element.className

          【讨论】:

            【解决方案5】:
            function btnclick()
            {
                  var txt=document.getElementId("<%=txt.ClientID%>");
                  txt.className="classname";
            }
            

            或者使用下面的jquery

            $("#txt").addClass("classname");
            $("#txt").removeClass("classname");
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-12-31
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-12-29
              • 2021-08-01
              • 1970-01-01
              相关资源
              最近更新 更多