css() 和 removeAttr() 方法
.css() jQuery 方法用于为所选元素设置或者返回一个或者多个样式属性。
.removeAttr() jQuery 方法从匹配元素集合中的每个元素中删除一个属性。
该方法使用 JavaScript removeAttribute() 函数,但它可以直接在 jQuery 对象上调用。
我们可以删除使用 JavaScript 和 jQuery 添加的样式。
但是,在本教程中,我们建议使用需要较少代码的 jQuery 方法。
让我们讨论以下场景:
if (color != 'ffffff') $("body").css("background-color", color); else //remove style ?
现在让我们删除样式。
空字符串将删除 CSS 颜色属性:
.css("background-color", "");
不要做 css("background-color", "none") 因为它会从 css 文件中删除默认样式。
还有另一种删除样式的方法。
只需使用 jQuery removeAttr() 方法:
removeAttr('style');
例子:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script> </head> <body> <h1 style="color:red">Red text </h1> <button>Remove</button> <script> $(document).ready(function() { $("button").click(function() { $("h1").removeAttr("style"); }); }); </script> </body> </html>
请注意,因为以下方法会删除 style 属性中的所有其他属性。
日期:2020-06-02 22:16:25 来源:oir作者:oir