jQuery css()方法
jQuery中的css()方法是用来改变所选元素的样式属性。这个方法可以以不同的方式使用。css()方法可以用来获取/返回所选元素的属性的当前值。
语法:
$(selector).css(property)
JavaScript
或者
$(selector).css(property, value)
JavaScript
或者
$(selector).css(property, function(index, currentvalue))
JavaScript
或者
$(selector).css({property:value, property:value, ...})
JavaScript
返回值:它将返回所选元素的属性值。
例子1:在这个例子中,我们将使用css()方法来获得段落元素的文本颜色。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<button>
Click here and it will return the
color value of p element
</button>
<p style="color:green">Welcome to gfg!</p>
</body>
<script>
(document).ready(function () {
// Here selecting button element
("button").click(function () {
// When the button is clicked, css() method
// will return the value using alert method
alert($("p").css("color"));
});
});
</script>
</html>
HTML
输出:
例子2:在这个例子中,我们将使用css()方法来改变选定元素的CSS样式。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<button>
Click here and it will change the
color of paragraph element
</button>
<p style="border: 2px solid green;
color:red;padding:5px">
Wecome to gfg!.
</p>
</body>
<script>
(document).ready(function () {
// Selecting button element
("button").click(function () {
// When the button is clicked css() method
// will change the color of paragraph
$("p").css("color", "green");
});
});
</script>
</html>
HTML
输出:
例子3:在这个例子中,我们将使用css()方法,用函数添加样式。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<button>
Click here and the padding will change.
</button>
<p style="border: 2px solid green;
color: green; padding: 5px;">
Welcome to gfg!.
</p>
<script>
(document).ready(function () {
("button").click(function () {
$("p").css("padding", function (h) {
return h + 30;
});
});
});
</script>
</body>
</html>
HTML
输出:
例子4:在这个例子中,我们将使用css()方法来同时应用多个CSS属性。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<p style="border: 2px solid green;color:green;padding:5px;">
Welcome to gfg!.
</p>
<button>Apply css</button>
<script>
("button").click(function () {
// Applying more than one property at a time
// Note: property name written in camelCase
("p").css({
"backgroundColor": "green",
"color": "white", "fontSize": "20px"
});
});
</script>
</body>
</html>
HTML
输出: