发布于:使用 jQuery 核心

CSS、样式和尺寸

jQuery 提供了一种方便的方式来获取和设置元素的 CSS 属性。

1
2
3
4
5
// Getting CSS properties.
$( "h1" ).css( "fontSize" ); // Returns a string such as "19px".
$( "h1" ).css( "font-size" ); // Also works.
1
2
3
4
5
6
7
8
9
// Setting CSS properties.
$( "h1" ).css( "fontSize", "100px" ); // Setting an individual property.
// Setting multiple properties.
$( "h1" ).css({
fontSize: "100px",
color: "red"
});

请注意第二行参数的样式——它是一个包含多个属性的对象。这是将多个参数传递给函数的常用方法,许多 jQuery setter 方法都接受对象来一次性设置多个值。

通常包含连字符的 CSS 属性需要在 JavaScript 中使用驼峰式命名法(camelCase)。例如,CSS 属性 font-size 在用作 JavaScript 中的属性名时表示为 fontSize。但是,当将 CSS 属性的名称作为字符串传递给 .css() 方法时,则不适用此规则——在这种情况下,驼峰式命名或连字符形式都可以使用。

不建议在可用于生产的代码中使用 .css() 作为 setter,但是在传入对象设置 CSS 时,CSS 属性将使用驼峰式命名法而不是连字符。

link 使用 CSS 类进行样式设置

作为 getter,.css() 方法很有价值。然而,在可用于生产的代码中,应普遍避免将其用作 setter,因为通常最好将展示信息排除在 JavaScript 代码之外。相反,为描述各种视觉状态的类编写 CSS 规则,然后更改元素的类。

1
2
3
4
5
6
7
8
9
10
11
// Working with classes.
var h1 = $( "h1" );
h1.addClass( "big" );
h1.removeClass( "big" );
h1.toggleClass( "big" );
if ( h1.hasClass( "big" ) ) {
...
}

类也可用于存储有关元素的状态信息,例如指示元素是否被选中。

link 尺寸

jQuery 提供了多种方法来获取和修改元素的尺寸和位置信息。

下面的代码简要概述了 jQuery 中的尺寸功能。有关 jQuery 尺寸方法的完整详细信息,请访问 api.jquery.com 上的尺寸文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Basic dimensions methods.
// Sets the width of all <h1> elements.
$( "h1" ).width( "50px" );
// Gets the width of the first <h1> element.
$( "h1" ).width();
// Sets the height of all <h1> elements.
$( "h1" ).height( "50px" );
// Gets the height of the first <h1> element.
$( "h1" ).height();
// Returns an object containing position information for
// the first <h1> relative to its "offset (positioned) parent".
$( "h1" ).position();