通过 jQuery,可以很容易地对 CSS 元素进行操作。
jQuery 操作 CSS
jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:
- addClass() - 向被选元素添加一个或多个类
- removeClass() - 从被选元素删除一个或多个类
- toggleClass() - 对被选元素进行添加/删除类的切换操作
- css() - 设置或返回样式属性
jQuery addClass() 方法
$("button").click(function(){ //向不同的元素添加 class 属性blue和important都是类名 $("h1,h2,p").addClass("blue"); $("div").addClass("important"); });您也可以在 addClass() 方法中规定多个类:
$("button").click(function(){ $("#div1").addClass("important blue"); });
jQuery removeClass() 方法
下面的例子演示如何不同的元素中删除指定的 class 属性:
$("button").click(function(){ $("h1,h2,p").removeClass("blue"); });
jQuery toggleClass() 方法
jQuery toggleClass() 方法。该方法对被选元素进行添加/删除类的切换操作:
jQuery css() 方法
css() 方法设置或返回被选元素的一个或多个样式属性。
返回 CSS 属性
如需返回指定的 CSS 属性的值,请使用如下语法:
css("propertyname");
$("p").css("background-color"); //返回首个匹配元素的 background-color 值
设置 CSS 属性
如需设置指定的 CSS 属性,请使用如下语法:
css("propertyname","value");
$("p").css("background-color","yellow"); //所有匹配元素设置 background-color 值
设置多个 CSS 属性
如需设置多个 CSS 属性,请使用如下语法:
css({"propertyname":"value","propertyname":"value",...});
$("p").css({"background-color":"yellow","font-size":"200%"});通过 jQuery,很容易处理元素和浏览器窗口的尺寸。
jQuery 尺寸 方法
jQuery 提供多个处理尺寸的重要方法:
- width()
- height()
- innerWidth()
- innerHeight()
- outerWidth()
- outerHeight()
jQuery width() 和 height() 方法
width() 方法设置或返回元素的宽度(不包括内边距、边框或外边距)。
height() 方法设置或返回元素的高度(不包括内边距、边框或外边距)。
$("button").click(function(){ var txt=""; txt+="Width: " + $("#div1").width() + "</br>"; txt+="Height: " + $("#div1").height(); $("#div1").html(txt); });
jQuery innerWidth() 和 innerHeight() 方法
innerWidth() 方法返回元素的宽度(包括内边距)。
innerHeight() 方法返回元素的高度(包括内边距)。
jQuery outerWidth() 和 outerHeight() 方法
outerWidth() 方法返回元素的宽度(包括内边距和边框)。
outerHeight() 方法返回元素的高度(包括内边距和边框)。
outerWidth(true) 方法返回元素的宽度(包括内边距、边框和外边距)。
outerHeight(true) 方法返回元素的高度(包括内边距、边框和外边距)。
设置指定的 <div> 元素的宽度和高度$("button").click(function(){ $("#div1").width(500).height(500); });