jQuery 擁有三種用於 CSS 操作的重要函數:
- $(selector).css(name,value)
- $(selector).css({properties})
- $(selector).css(name)
$(selector).css(name,value)用法樣本:為所有匹配元素的給定 CSS 屬性設定值
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color","red");
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body></html>
$(selector).css({properties}) 用法樣本:同時為所有匹配元素的一系列 CSS 屬性設定值
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").css({"background-color":"red","font-size":"200%"});
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>
$(selector).css(name) 用法樣本:返回指定的 CSS 屬性的值
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").click(function(){
$("#result").html($(this).css("background-color"));
});
});
</script>
</head>
<body>
<div style="width:100px;height:100px;
background:#ff0000"></div>
<p id="result">Click in the box</p>
</body>
</html>