发布在:使用 jQuery Core

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 设置器方法接受对象以一次设置多个值。

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

不建议在生产就绪代码中将 .css() 用作设置器,但当传入一个对象来设置 CSS 时,CSS 属性将采用驼峰式命名法,而不是使用连字符。

链接 使用 CSS 类进行样式设置

作为获取器,.css() 方法很有价值。但是,通常应该避免在生产就绪代码中将其用作设置器,因为通常最好将表示性信息排除在 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" ) ) {
...
}

类还可用于存储有关元素的状态信息,例如指示元素已选择。

链接 尺寸

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();