Guidelines for jQuery's css of method

  • 2020-06-03 05:52:44
  • OfStack

Definition and usage

The css() method returns or sets one or more style attributes of the matching element.

Returns the value of the CSS attribute

Returns the value of the CSS attribute for the first matched element.

Note: The abbreviated CSS attribute (such as "background" and "border") is not supported when used to return a value.


$(selector).css(name)

name required. Specifies the name of the CSS attribute. This parameter can contain any CSS attribute. Such as "color".

The instance
Gets the value of the color style property in paragraph 1:


$("p").css("color");

Set the CSS property

Sets the specified CSS attribute for all matched elements.


$(selector).css(name,value)

name required. Specifies the name of the CSS attribute. This parameter can contain any CSS attribute, such as "color".

value optional. Specifies the value of the CSS attribute. This parameter can contain any CSS attribute value, such as "red".

If an empty string value is set, the specified attribute is removed from the element.

The instance
Set all paragraphs to red:


$("p").css("color","red");

Use the function to set the CSS property

Sets the value of the style attribute in all matched elements.
This function returns the value of the property to set. It takes two arguments, index being the index position of the element in the collection of objects, and value being the original attribute value.


$(selector).css(name,function(index,value))

name required. Specifies the name of the CSS attribute. This parameter can contain any CSS attribute, such as "color".


function(index,value)

Specifies a function that returns the new value of the CSS attribute.
index - Optional. Accept the index location of the selector
oldvalue - Optional. Accepts the current value of the CSS attribute.

Example 1
Set all paragraphs to red:


$("button").click(function(){
$("p").css("color",function(){return "red";});
});

Example 2
Gradually increase the width of div:


$("div").click(function() {
$(this).css(
"width", function(index, value) {return parseFloat(value) * 1.2;}
);
});

Set multiple CSS property/value pairs


$(selector).css({property:value, property:value, ...})

Set the Name/value pair object to the style properties of all matching elements.
This is the best way to set a large number of style attributes on all matched elements.

{property:value}
A necessity. Specifies the Name/value pair object to set as a style property.
This parameter can contain several pairs of CSS attribute names/values. Such as {" color ":" red ", "font - weight" : "bold}"

The instance


$("p").css({
"color":"white",
"background-color":"#98bf21",
"font-family":"Arial",
"font-size":"20px",
"padding":"5px"
});

This is the end of this article, I hope you enjoy it.


Related articles: