Learning the attributes and styles of elements in jQuery (4) from scratch

Source: Internet
Author: User

I. Summary
This article explains how to use jQuery to obtain and operate the attributes and CSS styles of elements. The distinction between DOM attributes and element attributes is worth learning.

Ii. Preface
We have been able to fully control the jQuery packaging set through the previous chapters, whether by selecting an object through the selector, or deleting from the packaging set, filter elements. this chapter describes how to use jQuery to obtain and modify element attributes and styles.

3. differentiate DOM attributes and element attributes
An img Tag:



Generally, developers are used to calling id, src, alt, and other "attributes" of this element ". I call it "element attribute ". however, when parsed to a DOM object, the actual browser will finally parse the tag element into a "DOM object" and store the "element attribute" of the element as "DOM attribute ". the two are different.
Although we have set the relative path of the element src: images/image.1.jpg
However, in the "DOM attribute", it is converted to an absolute path: http: // localhost/images/image.1.jpg.

Even some "element attributes" and "DOM attributes" have different names. For example, the above element attribute class corresponds to the className after being converted to the DOM attribute.

Remember, in javascript, we can directly get or set the "DOM attribute ":
Copy codeThe Code is 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>

Therefore, to set the CSS style class of an element, you must use "DOM attribute" className "instead of" element attribute "class:

Img1.className = "classB ";

4. Operate "DOM attributes"
There is no function in jQuery to wrap "DOM attribute", because it is easy to use javascript to get and set "DOM attribute. the each () function provided by jQuery is used to traverse the jQuery package set. The this pointer is a DOM object, so we can apply this and use native javascript to manipulate the DOM attributes of the element:
Copy codeThe Code is 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 describes the each function:

Each (callback) Returns: jQuery package set
Run the callback Method on each element in the wrapper set. The callback method accepts a parameter to indicate the index value of the current traversal, starting from 0.

5. Operate "element attributes"
We can use getAttribute and setAttribute in javascript to operate the "element attribute" of an element ".
In jQuery, you are provided with the attr () set function, which can simultaneously manipulate the attributes of all elements in the Set:

Name Description Example

Attr (name)

Obtains the attribute value of the First Matching Element. This method can be used to conveniently obtain the value of an attribute from the First Matching Element. If the element does not have a property, undefined is returned. Return the src attribute value of the first image in the document:
$ ("Img"). attr ("src ");
Attr (properties)

Set an object in the form of "name/value" to the attributes of all matching elements.

This is the best way to set multiple attributes in batches among all matching elements. Note: To set the class attribute of an object, you must use 'classname' as the attribute name. Or you can directly use. addClass (class) and. removeClass (class ).

Set the src and alt attributes for all images:
$ ("Img"). attr ({src: "test.jpg", alt: "Test Image "});
Attr (key, value) Set an attribute value for all matching elements. Set the src attribute for all images:
$ ("Img"). attr ("src", "test.jpg ");
Attr (key, fn)

Set a calculated attribute value for all matching elements.

Instead of providing a value, a function is provided. The value calculated by this function is used as the attribute value.

Set the src attribute value to the title attribute value:
$ ("Img"). attr ("title", function () {return this. src });
RemoveAttr (name) Deletes an attribute from each matching element. Delete the src attribute of the image in the document:
$ ("Img"). removeAttr ("src ");
When the id selector is used, the jQuery package set with only one object is often returned. In this case, the attr (name) function is often used to obtain its element attributes:
Copy codeThe Code is as follows:
Function testAttr1 (event ){
Alert ($ ("# hibiscus"). attr ("class "));
}

Note that the attr (name) function returns only the attribute values of the First Matching element. The attr (key, name) function sets the attributes of all elements in the packaging set:
Copy codeThe Code is as follows:
// Modify the alt attribute of all img Elements
$ ("Img"). attr ("alt", "modified alt attributes ");

While attr (properties) can modify multiple element attributes at a time:
Copy codeThe Code is as follows:
$ ("Img"). attr ({title: "modified title", alt: "modifying alt attributes at the same time "});

In addition, although we can use removeAttr (name) to delete element attributes, the corresponding DOM attributes will not be deleted and will only affect the values of DOM attributes.

For example, if you remove the readonly attribute of an input element, the corresponding DOM attribute is changed to false (that is, the input is changed to editable State ):

$ ("# InputTest"). removeAttr ("readonly ");

6. Modify the CSS style
Modify the element style. You can modify the element CSS class or directly modify the element style.

One element can apply multiple css classes, but unfortunately stored in the DOM attribute using a string separated by spaces, rather than an array. therefore, if you want to add or delete multiple attributes to an element in the original javascript era, you must operate the string yourself.

JQuery makes all this very simple. We no longer need to do boring work.

1. Modify the CSS class
The following table shows the jQuery Method for modifying the CSS class:
Name Description Instance

AddClass (classes)

Add the specified class name for each matching element. Add the 'selected' class to the matched element:
$ ("P"). addClass ("selected ");
HasClass (class) Determine whether at least one element in the packaging set applies the specified CSS class.
$ ("P"). hasClass ("selected ");
RemoveClass ([classes]) Deletes all or specified classes from all matching elements. Delete the 'selected' class from the matched element:
$ ("P"). removeClass ("selected ");
ToggleClass (class) Delete (ADD) a class if it exists (does not exist. Switch the 'selected' class to the matching element:
$ ("P"). toggleClass ("selected ");
ToggleClass (class, switch) Add a class when switch is true,
Delete a class when switch is false.

Click to switch the highlighted style three times:
Var count = 0;
$ ("P"). click (function (){
$ (This). toggleClass ("highlight", count ++ % 3 = 0 );
});

Using the above method, we can modify the element's CSS class like a set, and no longer need to manually parse the string.

Note:AddClass (class) AndRemoveClass ([classes])Parameters can be input into multiple css classes at a time, separated by spaces, such:

$("#btnAdd").bind("click", function(event) { $("p").addClass("colorRed borderBlue"); });


The parameters of the removeClass method are optional. If no parameters are input, all CSS classes are removed:

 $("p").removeClass()

 

2. Modify the CSS style

Similarly, when we want to modify a specific CSS style of an element, that is, to modify the element attribute "style", jQuery also provides the corresponding method:

Name Description Instance
Css (name) Access the style attribute of the First Matching Element. Obtain the value of the color Style attribute of the first section:

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

Css (properties)

Set a "name/value pair" object to the style attribute of all matching elements.

This is the best way to set a large number of style attributes on all matching elements.

Set the font color of all paragraphs to red and the background to Blue:
$ ("P" ).css ({color: "# ff0011", background: "blue "});

Css (name, value)

Set the value of a style attribute among all matching elements.

The number is automatically converted to the pixel value.

Set the font of all paragraphs to Red:

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

 

7. obtain common attributes

Although we can obtain almost all information about elements by obtaining attributes, features, and CSS styles, pay attention to 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 object width</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 ("Width ():"+ $ ("# TestDiv"). Width ());// The correct value is 1264.Alert ("Style. width :"+ $ ("# TestDiv") [0]. style. width );// Null Value})</Script></Head><Body>  <Div Id= "TestDiv">Test text</Div></Body></Html>


We want to obtain the width of the test layer and use the attr method to obtain the "element feature" as undifined, because no width is added for the div. the css () method can be used to obtain the value of the style attribute, but different results are returned in different browsers. in IE6, auto is returned, while the correct value is returned in FF, it is followed by "px ". therefore, jQuery provides the width () method, which returns a correct value without px.

To solve the preceding problem, jQuery provides methods for obtaining and setting common attributes. For example, width () is used to obtain the width of an element, while width (val) is used to set the width of an element.

The following methods can be used to obtain common attribute values of an element:

1. Width and Height related Height and Width
Name Description Example
Height () Obtains the current calculated height (px) of the First Matching Element ). Obtain the height of the first section:
$ ("P"). height ();
Height (val) Set the CSS height (hidth) attribute value for each matching element. If the unit (such as em or %) is not explicitly specified, px is used. Set the height of all paragraphs to 20:

$ ("P"). height (20 );

Width () Obtains the current calculated width (px) of the First Matching Element ). Obtain the width of the first segment:
$ ("P"). width ();
Width (val)

Set the CSS width attribute value for each matching element.

If the unit (such as em or %) is not explicitly specified, px is used.

Set the width of all paragraphs to 20:

$ ("P"). width (20 );

InnerHeight ()

Obtain the height of the interior area of the First Matching Element (including the padding and not the border ).
This method is effective for both visible and hidden elements.

See the final example
InnerWidth ()

Obtain the width of the area inside the First Matching Element (including the padding and not the border ).
This method is effective for both visible and hidden elements.

See the final example
OuterHeight ([margin])

Obtain the external height of the First Matching Element (including the padding and border by default ).
This method is effective for both visible and hidden elements.

See the final example
OuterWidth ([margin])

Obtain the external width of the First Matching Element (including the padding and border by default ).
This method is effective for both visible and hidden elements.

See the final example

 

The differences between the "inner", "outer", and "height/width" functions are described as follows:

OuterWith can accept a bool value parameter to indicate whether to calculate the margin value.

I believe that this figure clearly shows the range requested by each function. The image uses width as an example to describe the function of height.

2. Positioning

In addition, in some design set pop-up object scripts, it is often necessary to dynamically obtain the pop-up coordinates and set the element position.

However, there are browser compatibility issues in many Location Calculation Methods. jQuery provides location-related functions for us:

Name Description Example
Offset ()

Obtains the relative offset of the matching element in the current window.

The returned object contains two integer attributes: top and left. This method is only valid for visible elements.

Get the offset of the second segment:
var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );
Position ()

Obtains the offset of a matched element from its parent element.

The returned object contains two integer attributes: top and left. For precise calculation results, use the pixel unit in the padding, border, and fill attributes. This method is only valid for visible elements.

Get the first offset:
var p = $("p:first");
var position = p.position();
$("p:last").html( "left: " + position.left + ", top: " + position.top );
ScrollTop ()

Obtains the offset of the matching element relative to the top of the scroll bar.

This method is effective for both visible and hidden elements.

Get the offset of the first segment relative to the top of the scroll bar:
var p = $("p:first");
$("p:last").text( "scrollTop:" + p.scrollTop() );
ScrollTop (val)

When passing the parameter value, set the vertical scroll bar top offset to this value.

This method is effective for both visible and hidden elements.

Set the vertical scroll bar value:
$("div.demo").scrollTop(300);
ScrollLeft ()

Returns the offset of the matching element to the left of the scroll bar.

This method is effective for both visible and hidden elements.

Get the offset of the first segment relative to the left of the scroll bar:
var p = $("p:first");
$("p:last").text( "scrollLeft:" + p.scrollLeft() );
ScrollLeft (val)

When passing the parameter value, set the left offset of the horizontal scroll bar to this value.

This method is effective for both visible and hidden elements.

Set the offset relative to the left of the scroll bar:
$("div.demo").scrollLeft(300);

 

8. Summary

This article describes how to use jQuery to operate on the attributes of elements and modify styles. please pay attention to the differences between element attributes and DOM attributes. the next article will explain the most important events and how to bind events and operate event objects.
Author: Zhang Ziqiu
Source: http://www.cnblogs.com/zhangziqiu/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.