Learning jQuery (4) from scratch-using jQuery to operate on attributes and styles of Elements

Source: Internet
Author: User
Document directory
  • 1. Width and Height related Height and Width
  • 2. Positioning

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:

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:

// Modify the alt attributes of all img elements $ ("img"). attr ("alt", "modified alt attributes ");

WhileAttr (properties) You can modify multiple element attributes at a time:

$ ("Img"). attr ({title: "modified title", alt: "modifying alt attributes at the same time "});

In addition, although we can useRemoveAttr (name)The element attribute is deleted, but the corresponding DOM attribute is not deleted, and only the DOM attribute value is affected.

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");
 
Modify 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()
 
Modify CSS styles

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 ");

Get common attributes

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);

Source: http://www.cnblogs.com/zhangziqiu/
 

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.