Js-dom2, form scripting

Source: Internet
Author: User
Tags tagname

DOM2:

1. DOM2: Create a complete HTML document

Document.implementation.createHTMLDocument ("New Doc");

alert (htmldoc.title);------"New Doc"

Alert (typeof htmldoc.body);-----"Object"

2. Style:

1) in CSS property is Color,background-image, in JS Style.color,style.backgroundimage

Float is a reserved word in JS, it cannot be used as a property name, the Style object is cssfloat, and in IE it is stylefloat

var A=document.getelementbyid ("Mydiv");

A.style.backgroundcolor= "Red";

2) Csstext: It can access the CSS code in the style attribute

mydiv.style.csstext= "Width:25px;height:100px;background-color:green";

alert (MyDiv.style.cssText);

3) GetPropertyValue (PropertyName): Returns the string value of the given property

var Prop,value,i,len;

for (i=0,len=mydiv.style.length;i<len;i++) {

Prop=mydiv.style[i]; or MyDiv.style.item (i);

Value=mydiv.style.getpropertyvalue (prop); ---string representation

Alert (prop+ ":" +value);

}

4) Returns the name of the CSS property at the given location

5) Removeproperty (PropertyName)

MyDiv.style.removeProperty ("border");

6) contains overlapping styles and affects the current element: the getComputedStyle () method, receives two parameters, obtains the calculated style element and a pseudo-element string (eg::after), if no pseudo-element is required, sets the second argument to NULL,

<style type= "Text/css" >

#myDiv {

Background-color:blue;

width:100px;

height:200px;

}

</style>

<div id= "mydiv" style= "border:1px solid black" ></div>

Js:

var Mydiv=document.getelementbyid ("Mydiv");

var computedstyle=document.defaultview.getcomputedstyle (mydiv,null);

alert (Computedstyle.backgroundcolor); ----RED

alert (computedstyle.width);

alert (computedstyle.border);-----Some browsers return 1px solid black

3, the Operation style sheet;

1)

var sheet=null;

for (Var i=0,len=document.stylesheets.length;i<len;i++) {

Sheet=document.stylesheets[i];

alert (SHEET.HREF);

}

2)

CSS rules:

Var Sheet=document.stylesheets[0]------First style sheet

Var Rules=sheet.cssrules | |   Sheet.rules; ----Get the Rules table

Var Rule=rules[0]--------------the first rule

Alert (Rule.selectortext); ---------------"Div. Box"

Alert (Rule.style.cssText); -----------CSS Code

To delete a rule:

function DeleteRule (sheet,index) {

if (sheet.deleterule) {

Sheet.deleterule (index);

}else if (sheet.removerule) {

Sheet.removerule (index); ----IE

}

}

DeleteRule (document.stylesheet[0],0);----Call function

4. Element size

1) Offset:

    • Offsethight: element occupies space vertically, element height + horizontal scrollbar height + top Border height + bottom border height
    • Offsetwidth: The amount of space the element occupies in the horizontal direction, similar to how the Offsethight is calculated
    • Offsetleft: The distance between the left bounding box of an element and the left inner border of the containing element
    • OffsetTop: The distance between the Sisu border of an element and the upper and inner border of the containing element

function Getelementleft (Element) {

Offsetleft and offsettop are related to the containing element, and the reference to the containing element is in offsetparent

var actualleft=element.offsetleft;

var current=element.offsetparent;

while (current!==null) {

Actualleft+=current.offsetleft;

Current=current.offsetparent;

}

return actualleft;

}

2) client area size: ClientWidth and clientheight (content area + inner margin height)

function GetViewport () {

if (document.compatmode== "Blackcompat") {

return{

Width:document.body.clientWidth;

Height:document.body.clientHeight;

};

}else{

return{

Width:document.documentElement.clientWidth;

Height:document.documentElement.clientHeight;

}

}

}

3) Scrolling Size:

Scollheight: The total height of the element content without a scroll bar

Scollwidth: The total width of the element content without scroll bars

Scollleft: The number of pixels that are hidden to the left of the content area, by setting this property to change the element's scroll position

Scolltop: The number of pixels that are hidden above the content area by setting this property to change the element's scroll position

var Docheight=math.max (Document.documentElement.scollHeight,

Document.documentElement.clientHeight);

var Docwidth=math.max (Document.documentElement.scollWidth,

Document.documentElement.clientWidth);

function Scolltotop (Element) {

if (element.scolltop!=0) {

Element.scolltop=0;

}}

5. Traverse:

1) Nodeinterator:4 A parameter, root, indicating which node to access the numeric code, Filter,false

When Filter==null, traverse all

var Div=document.getelementbyid ("Div1");

var filter=function (node) {

return Node.tagName.toLowerCase () = = "Li"?

Nodefilter.filter_accept:

Nodefilter.filter_skip;

}

var interator=document.createnodeinterator (Div,nodefilter.

Show_element,filter,false);

var node=interator.nextnode (); Previousnode ()

while (Node!=null) {

alert (node.tagname);

Node=interator.nextnode ();

}

2) TreeWalker

var walker=document.createtreewalker (Div,

Nodefilter.show_element,filter,false);

Walker.firstchild ();

Walker.nextsibling ();----Next sibling element

Walker CurrentNode----The current starting point

6. Scope in DOM:

1) createrange ():

Setstartbefore (Refnode):

Setstateafter (Refnode):

Setendbefore (Refnode):

Setendafter (Refnode):

eg

<p id= "P1" ><b>Hello</b> world</p>

var range1=document.createrange ();

Range2=document.createrange ();

P1=document.getelementbyid ("P1");

Range1.selectnode (p1);

Range2.selectnodecontents (p1);

Range1---><p id= "p1" ><b>Hello</b> world</p>

Range2---><b>Hello</b> world

2) var P1=document.getelementbyid ("P1");

Hellonode=p1.firstchild.firstchild; ----Hello

Worldnode=p1.lastchild; ----World

var range=document.createrange ();

Range.setstart (hellonode,2); ----Llo

Range.setend (worldnode,3); ----WO

<p><b>He</b><b>llo</b> world</p>

"World" will be divided into Wo and rld

3) range.deletecontents ();

Will output <p><b>He</b> rld</p>

4) Extractcontents () returns a range of text fragments

var fragment=range.extractcontents ();

P1.parentNode.appendChild (fragment);

<p><b>He</b> rld</p>

<b>llo</b> wo

5) Clonecontents () saves the copy in the range node, not the actual node

var fragment=range.clonecontents ();

P1.parentNode.appendChild (fragment);

<p><b>Hello</b> world</p>

<b>llo</b> wo

6) Insertnode () Inserts a node at the beginning of the range selection

var span=document.createelement ("span");

Span.style.color= "Red";

Span.appendchild (document.createTextNode ("inserted text"));

Range.insertnode (span);

Output: <p><b>he<span style= "color:red" >inserted text</span>llo</b> world</p>

7) Collapse to DOM range:

Range.collapse (TRUE); Collapse to start to true

8) Clear Dom Range

Range.detach ();//detach it from the document

Range=null;

Form script:

1. Documen.forms can get all the forms in the page

var firstform=document.forms[0];

var myform=document.forms["foem2"];

2. Submit the form:

1) <input type= "Submit" value= "Submit" >

Custom Submit button

<button type= "Submit" >submot</button>

Picture button

<input type= "image" src= "Gg.gif" >

2) Submit the button programmatically in JS:

var Form=document.getelementbyid ("MyForm");

Form.submit ();

However, the submit event is not triggered, so you need to validate the form data before calling this method

Repeating form submission:

Method 1:

var checksubmitflg = false;

function Checksubmit () {

if (!CHECKSUBMITFLG) {

First time Commit

CHECKSUBMITFLG = true;

return true;

} else {

Repeat Commit

Alert ("Submit again!");

return false;

}

}

Method 2:

Eventutil.addhandler (Form, "Submit", function (event) {

Event=eventutil.getevent (event);

var target=eventutil.gettarget (event);

var btn=target.elements["Submit-btn"];

Btn.disable=true;

})

4. Reset the form:

Form.reset (); Triggers the reset event as if the reset button is clicked

5. Form fields:

var Form=document.getelementbyid ("Form1");

Get the first field of a form

var field1=form.elements[0];

Get a field named TextBox1

var field2=form.elements["TextBox1"];

Get the number of fields contained in the form

var fieldcount=form.elements.length;

When multiple form controls use a name at the same time, a nodelist is returned

6. Common form Field Properties

Form---Pointer to the form that the current field belongs to, read-only

var Form=document.getelementbyid ("Form1");

var field=form.elements[0];

Alert (field.form===form)----Check the value of the form property

Field.focus (); ---Set focus to the current field

Form.disable=true; ----Disable the current field

7. Common form Field methods: Focus () and Blur ()

1) Focus (): Sets the focus of the browser to form fields, activates form fields so that they can respond to keyboard events

Eg: page loaded, move focus to the first field in the form

Eventutil.addhandler (window, "Load", function (event) {

Document.forms[0].elements[0].focus ();

});

HTML5 adds a autofocus property to the form element, which is a Boolean value (true in the supported browser) and automatically moves the focus to the corresponding field in the browser that supports the property <input type= "text" autofocus>;

2) blur () is the focus removed from the element

8. Common form Field events: Blur,focus,change (triggers when input and textarea elements lose focus and value changes, for select elements, when their options change)

9. Text Box script:

1) input cannot exceed 50 characters and can display 25 characters:

<input type= "text" size= "maxlength=" "value=" AAAA ">

2) cannot specify the maximum number of characters in textarea

<textarea rows= "cols=" 5 ">aaaa</textarea>

3) Select () selects all text in the text box, does not accept parameters and can be called at any time

var textbox=document.forms[0].elements["TextBox1"];

Textbox.select ();

4) Select event:

Selectionstart,selectionend: Holds a value based on 0, representing the range of text

function Getselecttext (textbox) {

Return textbox.value.substring (Textbox.selectionstart,textbox.selectionend)

}

5) Select part of the text: Setselectionrange () method

Receive two parameters: the index of the first character, the index of the last character, in IE8 and previous versions, this method is not supported

10. Filter Input:

1) Shielding characters

Eg: Only users are allowed to enter values:

Eventutil.addhandler (textbox, "KeyPress", function (event) {

Event=eventutil.getevent (event);

var target=eventutil.gettarget (event);

var charcode=eventutil.getcharcode (event);

Get character encoding across browsers

if (!/\d/.test (String.fromCharCode (charcode)) &&! Event.ctrlkey) {

String.fromCharCode (charcode)) converts character encoding into a string

Eventutil.preventdefault (event);

}

})

2) Manipulating the Clipboard

Beforecopy-occurs before the copy operation;

Copy

Beforecut:

Cut

Beforepaste:

Paste

3 Methods for Clipboarddata objects (accessing data in the Clipboard): GetData (data type), SetData (data type, text to be placed on the Clipboard), ClearData ()

11, automatically switch focus:

<input type= "text" name= "Tel1" id= "TextTel1" maxlength= "3" >

<input type= "text" name= "Tel2" id= "TextTel2" maxlength= "3" >

<input type= "text" name= "Tel3" id= "TextTel3" maxlength= "4" >

Js:

(function () {

function Tabforward (event) {

Event=eventutil.getevent (event);

var target=eventutil.gettarget (event);

if (target.value.length==target.maxlength) {

var form=target.form;

for (Var i=0,len=form.elements.length;i<len;i++) {

if (form.elements[i]==target) {

Form.elements[i+1].focus ()

}

Return

}

}

}

var Textbox1=document.getelementbyid ("TextTel1");

var Textbox2=document.getelementbyid ("TextTel2");

var Textbox3=document.getelementbyid ("TextTel3");

Eventutil.addhandler (textbox1, "KeyUp", Tabforward);

Eventutil.addhandler (TextBox2, "KeyUp", Tabforward);

Eventutil.addhandler (TextBox3, "KeyUp", Tabforward);

})()

12. HTML Constraints:

1) Required field: required

2) range of values: min,max,step (difference between maximum minimum two ticks)

<input type= "number" min= "0" max= "step=" 5 "name=" Count ">

The user can only enter a value between 0-100 and is a multiple of 5

Stepup (); The default value is 1, plus 1;

Stepdown (); The default value is 1, minus 1;

Stepdown (5); Minus 5

3) Input mode: pattern---regular expression

<input type= "Number" name= "Count" pattern= "\d+" >--input values

4) Detection Effectiveness

    1. Checkvalidity ()

if (document.forms[0].elements[0].checkvalidity ()) {

Field continues effectively

}else{

Invalid field

}

    1. The Validity property tells you whether the field is valid or invalid

if (input.validity && input.validity.valid) {

if (input.validity.valueMissing) {

Alert ("Please add us")

}else if (input.validity.typeMismatch) {

Alert ("Sssss")

}

}

5) Disable authentication: novalidate

13. Select Box Script---select,option

Add (New,rel);---the option, position before rel

Multiple---boolean value

Remove (Index)

selectindex:--based on the 0 checked index, if no item is selected, the value is-1, for multiple-selection controls, only the index of the first item is saved

Size---The number of rows visible in the selection box

Operation Options:

var selectbox=document.forms[0].elements["Location"];

var Text=selectbox.options[0].text;

var Value=selectbox.options[0].value;

1) Select option: SelectedIndex Property

Radio:

var selectedoption=selectbox.options[selectbox.selectedindex];

var Selectedindex=selectbox.selectedindex;

var selectedoption=selectbox.options[selectedindex];

Alert ("Selected index:" + selectedindex+ "\nselected text:" + selectedoption.text+ "\nselected value:" + Selectedoption.value);

Multi-select:

function Getselectedoptions (selectbox) {

var result=new Array ();

var option=null;

for (Var i=0,len=selectbox.options.length;i<len;i++) {

OPTION=SELECTBOX.OPTIONS[1];

if (option.selected) {

Result.push (option);

}

}

return result;

}

2) Add options:

The first type:

var newoption=new option ("option text", "option value");

Selectbox.add (newoption,undefined);

The second type:

AppendChild ()

3) Move:

var Selectbox1=document.getelementbyid ("selLocations1");

var Selectbox2=document.getelementbyid ("SelLocations2");

Selectbox2.appendchild (Selectbox1.options[0]);

The AppendChild () method passes in the existing element of a document, removes it from the parent node, and then adds it to the specified location

Reflow:

var optiontomove=selectbox.options[1];

Selectbox.insertbefore (Optiontomove,selectbox.options[optiontomove.index-1])

14. Rich Text editing:

1) Use Contenteditable property: true-Open; false-close; inherit-inherit

<div class= "Editable" id= "RichEdit" contenteditable></div>

var Div=document.getelementbyid ("RichEdit");

Div.contenteditable= "true";

Js-dom2, form scripting

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.