jQuery attributes and styles (6)
Get the style attribute on the dom element through JavaScript. We can dynamically assign style attributes to the element. In jQuery, if we want to dynamically modify the style attribute, we only need to use the css() method.
css() method: Get the calculated value of the element's style attribute or set the element's CSS attribute
Get:
css( propertyName ): Get the calculated value of the style attribute of the first element in the matching element collection
css( propertyNames ): Pass an array and return an object result
Settings:
css(propertyName, value): Set CSS
css(propertyName, function): You can pass in a callback function and return the corresponding value. Processing
css(properties): You can pass an object and set multiple styles at the same time
Note:
Browser properties are obtained in different ways. When obtaining certain values All jQuery uses unified processing, such as RBG for color and px for size. The css() method supports camel case writing and mixed case writing. Internal fault-tolerant processing is done.
When a number When used only as a value, jQuery will convert it to a string and add px to the end of the string, such as .css("width",50}) and .css("width", "50px"})
Let's take a look at a piece of code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <div>php 中文网</div> <script> $('div').css('color','red'); </script> </body> </html>
Change the style of the content in the div
Let's take a look below, what if we change multiple styles? , for example, if I want to set a width, height, or background for a div tag, how should I write it?
Then we will start writing a piece of code like this:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <div>php 中文网</div> <script> $("div").css({ width:'200px', height:'200px', background:'#ccc' }); </script> </body> </html>
Looking at the above code, we can set the width, height and background of the div to the style we want
Note: When we write, after writing an attribute, we need to end it with a comma. When we write the last one, we can not add a comma