I. Summary
This article explains how to use jquery to get and manipulate the attributes and CSS styles of elements. The distinction between DOM attributes and element attributes is worth learning.
two. Foreword
Through the previous chapters we have been able to fully control the jquery wrapper set, either by selecting objects from the selector, or by removing them from the wrapper set, filtering the elements. This chapter explains how to use jquery to get and modify element attributes and styles.
three. Distinguishing between DOM attributes and element attributes
An IMG tag:
Usually developers are accustomed to the ID, SRC, alt, and so called "attributes" of this element. I call it "element attributes." However, when parsing into a DOM object, the actual browser eventually resolves the label elements into "Dom objects" and stores the element attributes of the elements as "Dom properties". There is a difference between the two.
Although we set the element src is the relative path: images/image.1.jpg
However, it is converted to an absolute path in the DOM properties: http://localhost/images/image.1.jpg.
Even some of the "element attributes" and "Dom properties" have different names, such as the element attribute class above, which corresponds to the classname when converted to DOM attributes.
Keep in mind that in JavaScript we can get or set the DOM properties directly:
Copy Code code as follows:
<script type= "Text/javascript" >
$ (function () {
var img1 = document.getElementById ("Hibiscus");
alert (Img1.alt);
Img1.alt = "Change the alt element attribute";
alert (Img1.alt);
})
</script>
So if you want to set the CSS style class for the element, you want to use the DOM property className instead of the element attribute class:
Img1.classname = "CLASSB";
four. Manipulate DOM Properties
There is no wrapper in jquery for the function "Dom properties", because it is easy to get and set DOM properties using JavaScript. In jquery, the each () function is used to traverse the jquery wrapper set, where the this pointer is a DOM object, so we can apply this in conjunction with native JavaScript to manipulate the element's DOM properties:
Copy Code code as follows:
$ ("img"). each (function (index) {
Alert ("Index: + index +", ID: "+ this.id +", alt: "+ This.alt);"
This.alt = "Changed";
Alert ("Index: + index +", ID: "+ this.id +", alt: "+ This.alt);"
});
The following is a description of each function:
Each (callback) Returns:jquery wrapper set
Executes the callback method for each element in the wrapper set. Where the callback method takes a parameter that represents the index value of the current traversal, starting at 0.
five. Manipulating "element Properties"
We can use the getattribute and setattribute in JavaScript to manipulate element attributes of elements.
In jquery, you are provided with a attr () wrapper set function that can simultaneously manipulate the attributes of all elements in the wrapper set:
Name |
Description |
Example |
attr (name) |
Gets the property value of the first matching element. This method makes it easy to get the value of a property from the first matching element. Returns undefined if the element does not have a corresponding property. |
Returns the SRC attribute value of the first image in the document: $ ("img"). attr ("src"); |
Attr (properties) |
Sets an object of type "name/value" to the property of all matching elements. This is the best way to set many properties in batches in all matching elements. Note that if you want to set the class attribute of an object, you must use ' className ' as the property name. Or you can use the. addclass (Class) and. Removeclass (Class) directly. |
Set SRC and ALT attributes for all images: $ ("img"). attr ({src: "test.jpg", alt: "Test Image"}); |
attr (key, value) |
Sets a property value for all matching elements. |
To set the SRC attribute for all images: $ ("img"). attr ("src", "test.jpg"); |
attr (Key, FN) |
Sets a computed property value for all matching elements. Instead of providing a value, a function is provided that evaluates the value of the function as the property value. |
Set the value of the SRC attribute to the value of the title property: $ ("img"). attr ("title", function () {return this.src}); |
REMOVEATTR (name) |
Remove an attribute from each matching element |
Delete the src attribute of the image in the document: $ ("img"). Removeattr ("src");
|
When you use the ID selector, you often return a jquery wrapper set with only one object, which often uses the attr (name) function to obtain its element attributes:
Copy Code code as follows:
function TestAttr1 (event) {
Alert ($ ("#hibiscus"). attr ("class");
}
Note the attr (name) function returns only the specific element property value of the first matching element. and attr (key, name) sets the element attributes in all the wrapper set:
Copy Code code as follows:
Modify the ALT attribute for all IMG elements
$ ("img"). attr ("Alt", "Modified ALT attribute");
attr (properties) can modify multiple element properties at once:
Copy Code code as follows:
$ ("img"). attr ({title: "Modified title", alt: "Modify ALT attribute at the same time"});
In addition, although we can use REMOVEATTR (name) to delete element attributes, the corresponding DOM properties are not deleted and affect only the value of the DOM property.
For example, removing the readonly element attribute of an INPUT element causes the corresponding DOM property to become false (that is, input becomes editable):
$ ("#inputTest"). Removeattr ("ReadOnly");
Six, modify CSS style
To modify the style of an element, we can modify the element CSS class or directly modify the style of the element.
An element can apply multiple CSS classes, but unfortunately it is stored in a space-delimited string, rather than an array, in the DOM attribute. So if we want to add or remove multiple attributes to an element in the original JavaScript age, we have to manipulate the string ourselves.
jquery makes it all the easier. We don't have to do those boring jobs anymore.
1. Modify CSS Class
The following table is the JQuery method associated with modifying a CSS class:
Name |
Description |
Instance |
AddClass (classes) |
Adds the specified class name for each matching element. |
Add the ' selected ' class to the matching element: $ ("P"). AddClass ("selected"); |
Hasclass (Class) |
Determines whether at least one element in the wrapper set has the specified CSS class applied |
$ ("P"). Hasclass ("selected"); |
Removeclass ([classes]) |
Deletes all or a specified class from all matching elements. |
Remove the ' selected ' class from the matching element: $ ("P"). Removeclass ("selected"); |
Toggleclass (Class) |
Deletes (adds) a class if it exists (does not exist). |
Switch the ' selected ' class for matching elements: $ ("P"). Toggleclass ("selected"); |
Toggleclass (class, switch) |
Add a class when the switch is true, Delete class when switch is False |
Toggle Highlight Style Every three clicks: var count = 0; $ ("P"). Click (function () { $ (this). Toggleclass ("Highlight", count++% 3 = 0); }); |
Using the above method, we can modify the CSS class of the element like a collection, and no longer have to parse the string manually.
Note that the parameters of AddClass (Class) and removeclass ([classes]) can be passed into multiple CSS classes at a time, separated by spaces, such as:
$ ("#btnAdd"). Bind (function (event) {$ ("P"). AddClass ("colorred borderblue");
The parameters of the Removeclass method are optional and all CSS classes are removed if the argument is not passed in:
$ ("P"). Removeclass ()
2. Modify CSS Styles
Also, when we want to modify an element's specific CSS style, that is, to modify the element property "style", jquery provides the appropriate method:
name |
description |
instance |
CSS (nam e) |
|
$ ("P"). CSS ("color"); |
CSS (properties) |
Put a "name/value pair" Object Sets the style attributes for all matching elements. This is the best way to set a large number of style properties on all matching elements. The |
$ ("P"). CSS ({color: #ff0011, background: "Blue"} ); |
CSS (name, value) |
Seven. Get Common Properties
Although we can get almost all of the information for an element by getting attributes, attributes, and CSS styles, note the following experiment:
<!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <Html xmlns= "Http://www.w3.org/1999/xhtml"> <Head> <Title>Get the width of an object</Title> <Script Type= "Text/javascript" Src= "Scripts/jquery-1.3.2-vsdoc2.js"></Script><script type="Text/javascript"> $ (function() {Alert ("attr (\" width\ "):"+ $("#testDiv"). attr ("Width"));undifinedAlert"CSS (\" width\ "):"+ $("#testDiv"). CSS ("Width"));Auto (IE6) or 1264px (FF)Alert "#testDiv"). width ()); //correct numeric value 1264 alert ( "#testDiv") [0]. Style.width); //Null value}) </script> head> > <div id= " Testdiv "</div> </body> >
We want to get the width of the test layer and use the attr method to get the "element attribute" as undifined because no width is added to the Div. While using the CSS () method can get the value of the Style property, but the results returned in different browsers are different, IE6 returns auto, while FF returns the correct value, but with "px" behind it. So jquery provides the width () method, which returns the correct numeric value without PX.
For the above problem, jquery provides a way to get and set the commonly used properties, such as width (), where the user gets the breadth of the element, and width (val) is used to set the width of the element.
The following methods can be used to get common property values for an element:
1. Width and height correlation height and width
Name |
Description |
Example |
Height () |
Gets the height value (px) of the current calculation of the first matching element. |
Get the height of the first paragraph: $ ("P"). Height (); |
Height (val) |
Sets the value of the CSS height (hidth) property for each matching element. If no specified unit (such as: EM or%), use PX. |
Set the height of all paragraphs to 20:
$ ("P"). Height (20); |
Width () |
Gets the width value (px) currently computed for the first matching element. |
Get the width of the first paragraph: $ ("P"). width (); |
Width (val) |
Sets the value of the CSS width property for each matching element. If no specified unit (such as: EM or%), use PX. |
Set the width of all paragraphs to 20:
$ ("P"). Width (20); |
Innerheight () |
Gets the height of the inner area of the first matching element (including padding, excluding borders). This method is valid for both visible and hidden elements. |
See the final example |
Innerwidth () |
Gets the inner area width of the first matching element (including padding, excluding borders). This method is valid for both visible and hidden elements. |
See the final example |
Outerheight ([margin]) |
Gets the outer height of the first matching element (the default includes padding and borders). This method is valid for both visible and hidden elements. |
See the final example |
Outerwidth ([margin]) |
Gets the external width of the first matching element (the default includes padding and borders). This method is valid for both visible and hidden elements. |
See the final example |
The difference between the three functions of "inner", "outer" and "height/width" in getting a function of a long width is:
Outerwith can accept a bool value parameter to indicate whether the margin value is computed.
I believe this figure at a glance at the scope of the functions requested. Picture with width as an example, each function of height is the same.
2. Position-related positioning
Additionally, in some scripts that design a set of pop-up objects, you often need to dynamically get the pop-up coordinates and set the location of the elements.
But many of the computational location methods have browser compatibility issues, and jquery provides us with location-related functions:
Name |
Description |
Example |
Offset () |
Gets the relative offset of the matching element in the current window. The returned object contains two cosmetic properties: Top and left. This method is valid only for visible elements. |
Gets the offset of the second paragraph:
var p = $("p:last"); var offset = p.offset(); p.html( "left: " + offset.left + ", top: " + offset.top ); |
Position () |
Gets the offset of the matching element relative to the parent element. The returned object contains two cosmetic properties: Top and left. To accurately calculate the results, use pixel units on the filler, border, and fill properties. This method is valid only for visible elements. |
Gets the offset of the first paragraph:
var p = $("p:first"); var position = p.position(); $("p:last").html( "left: " + position.left + ", top: " + position.top ); |
ScrollTop () |
Gets the offset of the matching element relative to the top of the scroll bar. This method is valid for both visible and hidden elements. |
Gets the offset of the first paragraph relative to the top of the scroll bar:
var p = $("p:first"); $("p:last").text( "scrollTop:" + p.scrollTop() ); |
ScrollTop (Val) |
When a parameter value is passed, the top offset of the vertical scroll bar is set to that value. This method is valid for both visible and hidden elements. |
Set vertical scroll bar values:
$("div.demo").scrollTop(300);
|
ScrollLeft () |
Gets the offset of the matching element relative to the left side of the scroll bar. This method is valid for both visible and hidden elements. |
Gets the offset of the first paragraph relative to the left of the scroll bar:
var p = $("p:first"); $("p:last").text( "scrollLeft:" + p.scrollLeft() ); |
ScrollLeft (Val) |
When you pass a parameter value, set the horizontal scroll bar to the left offset to that value. This method is valid for both visible and hidden elements. |
Sets the offset on the left side of the scroll bar:
$("div.demo").scrollLeft(300);
|
Eight. Summary
This article mainly explains how to use jquery to manipulate the attributes of elements and modify styles. Please pay attention to the difference between the element attribute and the DOM property. The next article will explain the most important events, including how to bind events, manipulate event objects, and so on.
Author: Zhang Zixiu
Source: http://www.cnblogs.com/zhangziqiu/