jQuery查询库几乎支持层叠样式表(CSS)中包含的所有选择器。的css()方法中jQuery查询用于更改所选元素的样式属性。的css()在JQuery中可以以不同的方式使用。
css()方法可用于检查所选元素的属性的当前值:
语法如下:
$(selector).css(property)
返回值:
它会返回所选元素的属性值。
范例1:
Input: $("p").css("color");
Output: Output of the above input will return the
rgb() value of the element.
代码1:
<!DOCTYPE html>
< head >
< script src="https://ajax.googleapis.com/ajax/libs
/jquery/3.3.1/jquery.min.js">
// this is the link of JQuery CDN direct from the
// jquery website so that we can use all the
//function of JQuery css()
</ script >
</ head >
< body >
< button >Click here and it will return the color value
of p element</ button >
< p style = "color:green" >Wecome to gfg!</ p >
</ body >
< script >
$(document).ready(function() {
//here selecting button element
$("button").click(function() {
// here when the button is clicked css() method
// will return the value using alert method
alert($("p").css("color"));
});
});
</ script >
</ html >
输出如下:
在点击按钮之前-

点击按钮后,

css()方法还用于添加或更改所选元素的属性。
语法如下:
$(selector).css(property, value)
返回值:
这将更改所选元素的属性值。
范例2:
Input: $("p").css("color", "red");
Output: Output of the "p" element becomes red
whatever may be the color previously.
代码2:
<!DOCTYPE html>
< head >
< script src="https://ajax.googleapis.com/ajax/libs
/jquery/3.3.1/jquery.min.js">
// this is the link of JQuery CDN direct from
// the jquery website so that we can use all
// the function of JQuery css()
</ script >
</ head >
< body >
< button >Click here and it will return the color value
of p element</ button >
< p style = "border: 2px solid green;color:red;padding:5px" >
Wecome to gfg!.</ p >
</ body >
< script >
$(document).ready(function() {
// here selecting button element
$("button").click(function() {
// here when the button is clicked css()
// method will change the color of paragraph
$("p").css("color", "green");
});
});
</ script >
</ html >
输出如下:
在点击按钮之前-

点击按钮后,

css()方法可以使用函数来更改所选元素的css属性:
语法如下:
$(selector).css(property, function(index, currentvalue))
返回值:
它将返回所选属性的更改值。
范例3:
Input: $("p").css("padding", function(i){ return i+20;});
Output: Output will get is the paragraph with padding value
increases to "25px" whatever be the initial value.
代码3:
<!DOCTYPE html>
< head >
< script src="https://ajax.googleapis.com/ajax/libs
/jquery/3.3.1/jquery.min.js">
//this is the link of JQuery CDN direct from
//the jquery website so that we can use all
//the function of JQuery css()
</ 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 >
</ body >
< script >
$(document).ready(function() {
$("button").click(function() {
$("p").css("padding", function(h) {
return h + 30;
});
});
});
</ script >
</ html >
输出如下:
在点击按钮之前-

点击按钮后,
