JQuery给元素动态增删类或特性

背景:通过JQuery动态给Html元素增加、删除类或属性,使Html元素在不同的时刻呈现不同的样式,给用户更好的体验感觉。

如存在以下p片段和button按钮,代码如下:

1         <p id="pDisplay">现在的背景颜色是白色,点击按钮以后背景变为红色</p>
2         <button id="changeColor">更改颜色</button>

存在如下css代码:

1     <style>
2          .colorRed{
3         background-color:red;
4     }
5     </style>

存在如下JS代码:

        $("#changeColor").toggle(function () {
            $("#pDisplay").addClass("colorRed");
        },
        function () {
            $("#pDisplay").removeClass("colorRed");
        });

如上代码,当点击按钮以后,给$("#pDisplay")元素添加或移除css类colorRed,效果如下:

同理,可应用于attr()和removeAttr(),代码如下:

1 //Disabled 设置元素不可用:
2 
3 $(this).attr("disabled","disabled")
4 
5 //移除push元素的diasble特性:
6 
7 $("#push").removeAttr('disabled')
原文地址:https://www.cnblogs.com/SharpL/p/4687748.html