Home > Web Front-end > JS Tutorial > Dom learning summary and introduction to the use of examples_javascript skills

Dom learning summary and introduction to the use of examples_javascript skills

WBOY
Release: 2016-05-16 17:35:42
Original
1215 people have browsed it

1. Re-navigate to the specified address: navigate("http://www.jb51.net");

2,

(1. *setInterval executes the specified code at intervals. The first parameter is the string of the code, the second parameter is the interval time (unit: milliseconds), and the return value is the identifier of the timer. For example:

setInterval("alert('hello')",5000);

*clearInterval cancels the scheduled execution of setInterval, which is equivalent to Enabled=False in Timer. Because setInterval can set multiple timings, clearInterval must specify the identifier of the timer to clear, which is the return value of setInterval.

var intervalld= setInterval("alert('hello')",5000);
clearInterval(intervalld);

(2. setTimeout is also a scheduled execution, but it is not a scheduled execution like setInterval. Instead, it is only executed once after setting the time. clearTimeout is also a clearing timing.
It is easy to distinguish: Interval is timing; Timeout is timeout.

var timeoutld=setTimeout("alert('hello')",2000);
(3. Case: Realizing the effect of title bar revolving door, that is, the browser's title text scrolls to the right every 500ms

Copy code The code is as follows:

Marquee effect


/title & gt;
& lt; script type = "text/javascript" & gt;
Function Scroll () {
var Title = document.tital; (0);
          var last = title.substring(1, title.length); 🎜>                                            script>







3.

(1. onload: Triggered when the web page is loaded. The browser downloads the document and parses and executes it at the same time. It may happen that a certain element needs to be operated when JavaScript is executed. This element has not been loaded. If so, the operation must be done. The code is placed in the onload event of the body, or the JavaScript can be placed after the element. The onload event of the element is triggered when the element itself is loaded, and the onload in the body is completed.
(2. onunload: web page. Triggered after closing (or leaving). onbeforeunload: A confirmation message will pop up when the window leaves (such as moving forward, backward, or closing). For example: ? '">

4,

In addition to unique attributes, there are of course events for common HTML elements: onclick (click), ondblclick (double-click), onkeydown (key pressed), onkeyup (key released), onkeypress (click on the button) , onmousedown (mouse pressed), onmousemove (mouse moved), onmouseout (mouse leaves element range),
onmouseover (mouse moves to element range), onmouseup (mouse button released), etc.

5. Properties of window object

(1. window.location.href="http://www.sina.com.cn", redirect to the new address, has the same effect as the navigate method. window.location.reload() refreshes the page.
(2. window.event is a very important attribute, used to obtain information when an event occurs. Events are not limited to events of the window object. Events of all elements can obtain relevant information through the event attribute.
a. altKey attribute, boot type, indicates whether the alt key is pressed when an event occurs. Similar attributes include ctrlKey and shiftKey

Copy code The code is as follows:

windows event example







"
="Click" onclick="if(window.event.ctrlKey){alert('Ctrl pressed')}else{alert('Normal click')}" />                                                  : //www.baidu.com "Onclight =" Alert ('Forbidden access!'); Window.event.returnValue = false; px " >

;




b. clientX, clientY are the coordinates of the mouse in the client area (in the browser page) when events occur; screenX, screenY are the coordinates of the mouse on the screen when events occur; offsetX, offsetY are when events occur relative to the mouse relative to the event source ( Button button) coordinates.
c, returnValue attribute, if returnValue is set to false, the processing of the default event will be cancelled.
d, srcElement: Get the event source object
e, KeyCode: the key value when the time occurs
f, button: the mouse button when the time occurs, 1 is the left button, 2 is the right button, 3 is the left button keys simultaneously.

                                      

6. clipboardData object, operations on the pasteboard. clearData("Text") clears the pasteboard; getData("Text") reads the value of the pasteboard, and the return value is the content of the pasteboard; setData("Text",val), sets the value of the pasteboard.

(1. When copying, the oncopy method of body is triggered. Directly return false to prohibit copying.
(2 , many elements also have oncopy and onpaste events

.

Example 1: No copying

Example 3: Disable pasting into text box

Please enter your mobile phone number:

Please enter your mobile phone number again: :

Example 4: Attached content when copying

When copying articles on the website, in order to prevent copyists from not adding the source of the article, a copyright statement is automatically added after the copied content.

function modifyClipboard(){

clipboardData.setData('Text',clipboardData.getData('Text') 'This article comes from the Blog Park Technology Zone, please indicate the source when reprinting.' location.href);

}

oncopy="setTimeout ('modifyClipboard()',100)".


The user will modify the content in the pasteboard 0.1 seconds after the copy action occurs. 100ms is just a common value, you can write 1000, 10, 50, 20... You cannot directly perform operations on the pasteboard in oncopy, so set a timer to execute it after 0.1 seconds, so that it is no longer on the oncopy execution call stack.

7. Page forward and backward: history operation history

window.history.back() goes back; window.history.forward() goes forward. You can also use window.history.go(-1) to move forward; window.history.go(1) to move backward.

Example 1:

This is page 2Back


8. Document attribute (the most complex attribute) document is an attribute of the window object. Because the window can be omitted when using the window object members, document is generally written directly.

(1. Write: Write content to the document. writeln is similar to write, except that a carriage return is added at the end (2.

(3. Code written in onclick and other events will flush out the content of the page, and will only be displayed when the page is loaded. During the write process, the write will be integrated with the original content

(4.

Case 1:


Copy code The code is as follows:
Copy code
The code is as follows:

getElementByName



Example of getElementByName< /title> Unlike foreach in C#, for (var r in radios) does not traverse each element, but traverses the key<BR> for (var r in radios) {<BR> alert(r.value);< : 🎜>          } <BR> }<BR> function btnClick2() {<BR> var inputs = document.getElementsByTagName("input");<BR> for (var i = 0; i < inputs.length; i ) {<BR> var input = inputs(i);<BR>                                                                                                                                                                     lt ;body><br>  <input type="radio" name="gender" value="Male" />Male<br>  <input type="radio" name="gender" value="Female" / >Female<br>  <input type="radio" name="gender" value="Confidential" />Confidential<br>  <input type="button" value="click" onclick="btnClick() " /><br> " <br /><br> " <input type="text" /><br /><br> " <input type="text" /><br /><br>  <input type="text" /><br /><br>  <input type="text" /><br /><br>  <input type ="text" /><br /><br>  <input type="button" value="bytagname" onclick="btnClick2()" /><br> </body><br> </html><br><br><br>Case 3: <br><br><br><br><br>Copy code<br><br><br> The code is as follows:<br><div class="codebody" id="code77712"> <br>getElementByTagName <br> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br> <html xmlns="http://www.w3.org/1999/xhtml"><br> <head><br>     <title>getElementByTagName
    
 

 
    
    
    
    
    
 
 

案例4:
复制代码 代码如下:

Read protocol wait timer


                                                                                                                                                                       var leftTime = 10;
var TimeID;
function scroll() {//alert(222);
var btn = document.getElementById("btnAgree");
//If the web page is very slow, it may be timed The control has not been loaded when the server is running!
                                                                                                                                                                btn.disabled = "";
                                                                                                                         value = "Please read the agreement and agree (there are " leftTime " seconds left)";
                       leftTime--;                                              
                                                                                                                     gt;


     




Case 5:




Copy code


The code is as follows:

Beauty Clock



Welcome to daomul Welcome to my blog, thank you






< ;/html>


16. Form form: The Form object is the Dom object of the form.

Method: submit() submits the form, but does not trigger the onsubmit event. Implement autopost, that is, the page is submitted immediately after the focus leaves the control, instead of submitting only after the submit button is submitted. When the cursor leaves, the onblur event is triggered, and the submit method of the form is called in onblur. After clicking submit, the onsubmit event of the form is triggered. Data verification can be performed in onsubmit. If there is a problem with the data, return false to cancel the submission.

Case 1:




Copy code

The code is as follows:

Form



Welcome to daomul’s blog, welcome again, thank you (Form form submission 4)



                                                                                                                                 " ")" Value = "button" /& gt;
& lt; input type = "Button" onClick = "Document.GetelementByid ('BTN1'). >                                              < . Autopostback in .net (the same is the submit call of the onblur method that is moved after the text box is entered)-->
                                                                                                                                           submit()">
 tion>
                                                                  ;/option>
                                                                                          

*Methods to create regular expression classes in JavaScript:
var regex = new RegExp("\d{5}") or var regex = /d{5}/
/ Expression/ is JavaScript The syntax provided in
is specially provided to simplify the writing of regular expressions. Regular expressions written in // do not need to worry about escape characters.
*Methods of the RegExp object:
** test(str) Determines whether the string str matches a regular expression, equivalent to IsMatch
var regex = /. @. /;
alert(regex. test("a@b.com"));
alert(regex.test("ab.com"));
** exec(str) performs search and matching, and the return value is the matching result (*)
** compile Compile expressions to improve running speed. ( * )
*String object provides some methods related to regular expressions, which are equivalent to wrapping the RegExp class to simplify the call: match(regexp), which is equivalent to calling exec


var s = "aaa@163.com";
var regex = /(. )@(. )/;
var match = s.match(regex);
alert(RegExp. $1 ", server: " RegExp.$2);

Case 1:




Copy code

The code is as follows:


Regular Expression



                                                                                                                                                                                        ; var regex = /(.)@(.) /;
s.match (regex);
Alert (regexp. $ 1); // >                     alert(RegExp.$2);                                                                                                                               ;/html>


18. Differences between different browsers



19. Keyboard code operation and financial box cases:

Case 1:

The text boxes involving amounts in financial related systems have the following requirements:

*Enter the amount text text box and do not use the Chinese input method. Non-numbers cannot be entered. When the focus is in the text box, the text box is left aligned; when the focus leaves the text box, the text box is right aligned and displays thousands. Disable input method: style=" ime-mode:disabled"
* It is forbidden to type illegal values, only these can be typed (k == 9) || (k == 13) ||

(k==46)||(k==8)||( k==189)||(k==109)||(k==190)||(k==110)|| (k>=48 &&

k<=57)||(k> =96 && k<=105)||(k>=37 && k<=40) . onkeydown="return

numonKeyDown()" Do not write onkeydown="numonKeyDown()" to distinguish between event response functions and functions called by event response functions.

* Disable pasting (great Tester), to get the value in the pasteboard, and then traverse each character to see if it is a legal value. Pasting is only allowed if all are legal values, as long as there is an illegal value Pasting is prohibited. charAt, charCodeAt method to add thousandth place

* Left-aligned without thousandths when the focus is on, right-aligned when the focus is not: this.style.textAlign='right'




Copy code


The code is as follows:


Financial text box settings





                                                                                                                                                                                                       
var k = window.event.keyCode;
return isValidNum(k);
}
//Determine whether k is legal Ascii
function isValidNum(k) {
return ((k == 9) || (k == 13) || (k == 46) || (k == 8) || (k == 189) || (k == 109) || ( k == 190) || (k == 110) || (k >= 48 && k <= 57) || (k >= 96 && k <= 105) || (k >= 37 && k <= 40));
}
//Add thousandths
function commafy(n) {
(d{3}) $)/g;
                                 //var n1 = n.replace(/^(d )/((.d )?)$/,function(s,s1,s2){return s1 .replace(re,"$,") s2;});
re = /(d{1,3})(?=(d{3}) (?:$|D))/g;<​​​        var text = window. clipboardData.getData("Text");
for (var i = 0; i < text.length; i ) {
var asc = text.charCodeAt(i); //charAt→"3", charCodeAt() gets the ASCII code
if (!isValidNum(asc)) { //When encountering an illegal value, the content to be pasted is considered illegal return false
return false;
}
                                                                                                                                                           9;}">
Cannot enter non-numbers:



  Disable input method:



  Cannot enter and paste non-digits:



  Add and remove thousandths:
onblur="this.value=commafy(this.value);this.style.textAlign='right';"
onfocus="this.style.textAlign='left'; this.value=this.value.replace(/,/g,'')" />






Copy code The code is as follows:

Province and city selection




Welcome to daomul's blog, welcome again, thank you (province and city selection)

 

 
    

        

        

        

        

        


            
            
            
        


    

 
 

案例4:权限选择
复制代码 代码如下:

Permission selection



Welcome to daomul Blog, welcome back, thank you (permission selection)
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template