jQueryCSS操作

1.css()方法

a)定义和用法:

i.css()方法返回或设置匹配的元素的一个或多个样式属性

b)返回css属性值:

i.返回第一个匹配元素的css属性值

c)注释:

i.当用于返回一个值时,不支持简写的css属性

d)语法:

i.$(selector).css(name)

1.解释:name必需。规定css属性的名称。该参数可包含任何css属性

e)实例:

i.取得第一个段落的color样式属性的值

<html>

<head>

<script type="text/javascript" src="/jquery/jquery.js"></script>

<scripttype="text/javascript">

$(document).ready(function(){

$("button").click(function(){

alert($("p").css("color"));

});

});

</script>

</head>

<body>

<p style="color:red">This is a paragraph.</p>

<button type="button">返回段落的颜色</button>

</body>

</html>

2.设置css属性

f)设置所有匹配元素的指定css属性

g)语法

i.$(selector).css(name,value);

ii.Name:必需,规定css属性的名称,该参数可包含任何css属性

iii.Value:可选,规定css属性的值,该参数可包含任何css属性值

h)实例

<html>

<head>

<script type="text/javascript"src="/jquery/jquery.js"></script>

<script type="text/javascript">

$(document).ready(function(){

$("button").click(function(){

$("p").css("color","red");

});

});

</script>

</head>

<body>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

<button type="button">改变段落的颜色</button>

</body>

</html>

3.使用函数来设置css属性

i)设置所有匹配的元素中样式属性的值

j)此函数返回要设置的属性值。接受两个参数,index为元素在对象集合中的索引位置,value是原先的属性值。

k)语法:

i.$(selector).css(name,function(index,value))

l)说明:

i.Name:必需,规定css属性的名称。该参数可包含任何css属性。

ii.Function(index,value)规定返回css属性新值的函数

1.index:可选,接受选择器的index位置

2.oldvalue:可选,接受css属性的当前值

m) 实例1:将所有段落的颜色设为红色

<html>

<head>

<scripttype="text/javascript"src="/jquery/jquery.js"></script>

<scripttype="text/javascript">

$(document).ready(function(){

$("button").click(function(){

$("p").css("color",function(){

return"red";

});

});

});

</script>

</head>

<body>

<p>This is aparagraph.</p>

<p>This is anotherparagraph.</p>

<button>设置所有 p 元素的color 属性</button>

</body>

</html>

n)实例2:逐渐增加div的宽度

<html>

<head>

<script type="text/javascript"src="/jquery/jquery.js"></script>

<scripttype="text/javascript">

$(document).ready(function(){

$("div").click(function() {

$(this).css(

"width", function(index, value) {return parseFloat(value) *1.2;}

);

});

});

</script>

<style>

div {width:100px; height:50px; background-color:red;}

</style>

</head>

<body>

<div>请点击这里</div>

</body>

</html>

4.设置多个css属性/值对

语法:$(selector).css(property:value,property:value,…)

说明:把“名/值对”对象设置为所有匹配元素的样式属性

这是一种在所有匹配的元素上设置大量样式属性的最佳方式。

Property:value,必需,规定要设置为样式属性的“名称/值对”对象。该参数可包含若干对css属性名称。

实例:

<html>

<head>

<script type="text/javascript"src="/jquery/jquery.js"></script>

<scripttype="text/javascript">

$(document).ready(function(){

$("button").click(function(){

$("p").css({

"color":"white",

"background-color":"#98bf21",

"font-family":"Arial",

"font-size":"20px",

"padding":"5px"

});

});

});

</script>

</head>

<body>

<p>This is a paragraph.</p>

<p>This is anotherparagraph.</p>

<button type="button">改变段落的样式</button>

</body>

</html>