JQuery:JQuery 中的CSS()方法

时间:2023-03-09 07:50:41
JQuery:JQuery 中的CSS()方法

JQuery:CSS()方法
jQuery css()方法:css()方法设置或返回被选元素的一个或多个样式属性。
1、返回 CSS 属性
如需返回指定的 CSS 属性的值,请使用如下语法:
css("propertyname");
下面的例子将返回首个匹配元素的 background-color 值:
实例:$("p").css("background-color");
代码如下:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>JQuery的使用!!!</title>
<script src="jquery-3.1.0.js"></script>
<script>
$(document).ready(function(){
//返回p元素的background-color
$("button").click(function(){
alert("p元素的背景色是:"+ $("p").css("background-color"));
});
});
</script> </head>
<body>
<h2>这是一个标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<button>返回p元素的background-color</button>
</body>
</html>

JQuery:JQuery 中的CSS()方法 JQuery:JQuery 中的CSS()方法

2、设置 CSS 属性
如需设置指定的 CSS 属性,请使用如下语法:
css("propertyname","value");
下面的例子将为所有匹配元素设置 background-color 值:
实例:$("h2").css("background-color","yellow");
代码如下:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>JQuery的使用!!!</title>
<script src="jquery-3.1.0.js"></script>
<script>
$(document).ready(function(){
//设置h2元素的background-color
$("button").click(function(){
$("h2").css("background-color","yellow");
});
});
</script> </head>
<body>
<h2>这是一个标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<button>设置h2元素的background-color</button>
</body>
</html>

JQuery:JQuery 中的CSS()方法 JQuery:JQuery 中的CSS()方法

3、设置多个 CSS 属性
如需设置多个 CSS 属性,请使用如下语法:
css({"propertyname":"value","propertyname":"value",...});
下面的例子将为所有匹配元素设置 background-color 和 font-size:
实例:$("h2").css({"background-color":"yellow","font-size":"200%"});

代码如下:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>JQuery的使用!!!</title>
<script src="jquery-3.1.0.js"></script>
<script>
$(document).ready(function(){
//设置h2元素的多个css属性
$("button").click(function(){
$("h2").css({"background-color":"yellow","font-size":"50%"});
});
});
</script> </head>
<body>
<h2>这是一个标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<button>设置h2元素的多个css属性</button>
</body>
</html>

JQuery:JQuery 中的CSS()方法 JQuery:JQuery 中的CSS()方法