Skip to content

jQuery css()

jQuery 提供了几种与 HTML 元素样式交互的方式,主要是通过 .css() 方法和类操作方法。

使用 .css() 方法可以获取单个 CSS 属性的计算值,或为选定的元素设置一个或多个 CSS 属性。

要检索匹配集合中第一个元素的特定 CSS 属性的当前值:

// Get the background color of the first paragraph
let bgColor = $("p").css("background-color");
console.log(bgColor); // Outputs the computed background color (e.g., "rgb(255, 255, 0)" or "transparent")

为所有匹配的元素设置特定的 CSS 属性:

// Set the background color for all paragraphs
$("p").css("background-color", "yellow");
// Property names can be camelCased or hyphenated
$("p").css("fontSize", "1.2em"); // CamelCase
$("p").css("font-weight", "bold"); // Hyphenated

要一次设置多个 CSS 属性,可以传递一个包含属性-值对的对象:

// Set background color and font size for all paragraphs
$("p").css({
"background-color": "lightblue",
"font-size": "110%",
"padding": "10px" // Quotes around properties are optional if valid JS identifiers
});

最佳实践:使用类进行样式设置

Section titled “最佳实践:使用类进行样式设置”

虽然 .css() 方法对于获取样式值或应用简单的动态样式更改很有用,但通常更好的实践是在 CSS 文件中使用类定义样式,然后使用 jQuery 添加或删除这些类。

为什么要使用类?

  • 关注点分离: 将样式规则放在 CSS 文件中,行为逻辑放在 JavaScript 文件中,使代码更清晰,更易于维护。
  • 可重用性: CSS 类可以在多个元素和页面之间轻松重用。
  • 性能: 操作类通常比直接设置多个内联样式性能更高。
  • 可维护性: 通过修改 CSS 文件而不是在 JavaScript 代码中搜索,更容易在整个站点范围内更新样式。
  • .addClass():向选定的元素添加一个或多个类。
  • .removeClass():从选定的元素中移除一个或多个类。
  • .toggleClass():如果指定类不存在则添加,如果存在则移除。
  • .hasClass():检查任何选定的元素是否具有特定类。

使用类的示例:

style.css
.highlight {
background-color: yellow;
font-weight: bold;
}
.disabled {
opacity: 0.5;
cursor: not-allowed;
}
script.js
// Add highlight class to all paragraphs
$("p").addClass("highlight");
// Remove highlight class from the first paragraph
$("p").first().removeClass("highlight");
// Toggle the disabled class on a button
$("#myButton").toggleClass("disabled");
// Check if an element is highlighted
if ($("#myDiv").hasClass("highlight")) {
console.log("Div is highlighted!");
}

当你需要获取计算后的样式值,或者应用一个不容易用预定义类表示的非常特定、动态的样式时,可以使用 .css()。对于大多数由用户交互或应用程序状态触发的样式更改,优先选择操作类。

要全面了解所有 jQuery CSS 和类操作方法,请查阅官方 jQuery API 文档。