jQuery css()方法 用于设置或获取元素的css样式,它是我们做出网页动态效果的常用方法。

语法

//获取css样式
$(selector).css("propertyname");
//设置css样式
$(selector).css("propertyname","value");   
//设置多个css样式
$(selector).css({"propertyname":"value","propertyname":"value",...}); 

其中propertyname为css的参数名,value为css的参数值。

比如 background-color:red; propertyname为background-color,value为red;

例子

例1

获取css样式的方法例子:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#html").text($("p").css("background-color"));
    });
});
</script>
</head>
<body>
<h2>jQuery css() 方法例子</h2>
<div id="html"></div>
<p style="background-color:#ff0000">本段的背景色为red.</p>
<p style="background-color:#00ff00">本段的背景色为绿色。</p>
<p style="background-color:#0000ff">本段背景色为蓝色。</p>
<button>点击这里获取第一个匹配元素的背景颜色</button>
</body>
</html> 
效果

jQuery css() 方法

例2

设置css样式的方法

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").css("background-color", "pink");
    });
});
</script>
</head>
<body>
<p style="background-color:#ff0000">本段背景色为红色。</</p>
<p style="background-color:#00ff00">本段的背景色为绿色。</</p>
<p style="background-color:#0000ff">本段的背景色为蓝色。</</p>
<p>这一段没有背景色。 </p>
<button>点击这里设置所有匹配元素的背景色</button>
</body>
</html>

例3 

设置多个css样式

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").css({"background-color": "yellow", "font-size": "120%"});
    });
});
</script>
</head>
<body>
<h2>这是一个标题</h2>
<p style="background-color:#ff0000">本段的背景色为red.</p>
<p style="background-color:#00ff00">本段的背景色为绿色。</p>
<p style="background-color:#0000ff">本段背景色为蓝色。</p>
<p>这一段没有背景色。</p>
<button>点击这里为所有选中的元素设置多种样式。</button>
</body>

</html>
效果

jQuery css() 方法