JavaScript code analysis

Source: Internet
Author: User

JavaScript code analysis
JavaScript code analysis


Example 1: DIV that follows the mouse


CSS style:
<Style>
# Div1 {width: 100px; height: 100px; background: red; position: absolute ;}
</Style>
# Div1 id selector, with the length, width, height, background color, and absolute position


JavaScript code:
<Script>
// Move the mouse within the page range
Document. onmousemove = function (ev ){
Var oEvent = ev | event;
Var oDiv = document. getElementById ('div1 ');

Var scrollTop = document.doc umentElement. scrollTop | document. body. scrollTop;
Var scrollLeft = document.doc umentElement. scrollLeft | document. body. scrollLeft;

ODiv. style. left = oEvent. clientX + scrollLeft + 'px ';
ODiv. style. top = oEvent. clientY + scrollTop + 'px ';
}


</Script>
Code Analysis:
Document. onmousemove = function (ev) indicates that the mouse moving event is on the entire page, and ev indicates passing parameters.
Var oEvent = ev | event; ensures browser compatibility
Var oDiv = document. getElementById ('div1 '); defines the object oDiv, which is obtained by obtaining the element id
Var scrollTop = document.doc umentElement. scrollTop | document. body. scrollTop; defines a High visible area and takes browser compatibility into account.
Var scrollLeft = document.doc umentElement. scrollLeft | document. body. scrollLeft; defines the visible area width and takes browser compatibility into account.
ODiv. style. left = oEvent. clientX + scrollLeft + 'px '; assign a value to the x coordinate of div1
ODiv. style. top = oEvent. clientY + scrollTop + 'px '; assign values to y coordinates of div1
The above two items can determine the location of div1, so that when the mouse moves the event, div1 will move together




Example 2: Control div movement by keyboard


CSS style:
<Style>
# Div1 {width: 100px; height: 100px; background: red; position: absolute ;}
</Style>


JavaScript code:
<Script>
Document. onkeydown = function (ev ){
Var oEvent = ev | event;
Var oDiv = document. getElementById ('div1 ');

If (oEvent. keyCode = 37) {// left
ODiv. style. left = oDiv. offsetLeft-10 + 'px ';
} Else if (oEvent. keyCode = 39) {// right
ODiv. style. left = oDiv. offsetLeft + 10 + 'px ';
}
Else if (oEvent. keyCode = 38) {//
ODiv. style. top = oDiv. offsetTop-10 + 'px ';
}
Else if (oEvent. keyCode = 40) {// right
ODiv. style. top = oDiv. offsetTop + 10 + 'px ';
}
}
</Script>
Code Analysis:
The keyCode is added to most of the knowledge points here. This is a keyboard event. Each key on the keyboard corresponds to a number, and the numbers at the top left and bottom right are 37, 38, 39,40, respectively,
In addition, the Branch Structure is if () {} else if (){},
OEvent. keyCode = 37 condition judgment,
ODiv. style. left = oDiv. offsetLeft-10 + 'px '; here, the left and right positions of div1 are assigned, followed by oDiv. offsetLeft-10 + 'px 'can be used to obtain the left margin of div1. Here, we move it to the left, because the left margin is reduced. And so on: The left margin increases, the right margin decreases, and the top margin moves up; the top margin increases and moves down.




Example 3: Drag


CSS style:
<Style>
# Div1 {width: 100px; height: 100px; background: red; position: absolute ;}
</Style>


JavaScript code:
<Script>
Window. onload = function ()
{
Var oDiv = document. getElementById ('div1 ');

Var disX = 0;
Var disY = 0;

ODiv. onmousedown = function (ev)
{
Var oEvent = ev | event;

DisX = oEvent. clientX-oDiv.offsetLeft;
DisY = oEvent. clientY-oDiv.offsetTop;

Document. onmousemove = function (ev)
{
Var oEvent = ev | event;
Var l = oEvent. clientX-disX;
Var t = oEvent. clientY-disY;

If (l <0)
{
L = 0;
}
Else if (l> document.doc umentElement. clientWidth-oDiv.offsetWidth)
{
Lw.document.doc umentElement. clientWidth-oDiv.offsetWidth;
}

If (t <0)
{
T = 0;
}
Else if (t> document.doc umentElement. clientHeight-oDiv.offsetHeight)
{
Tsf-document.doc umentElement. clientHeight-oDiv.offsetHeight;
}

ODiv. style. left = l + 'px ';
ODiv. style. top = t + 'px ';
};

Document. onmouseup = function ()
{
Document. onmousemove = null;
Document. onmouseup = null;
};

Return false;
};
};
</Script>
Code Analysis:
Window. onload = function (){


} The function executed when the window is loaded
Var disX = 0; var disY = 0; define two variables and assign 0 values.
ODiv. onmousedown = function (ev ){
Document. onmousemove = function (ev ){


}
Document. onmouseup = function (){

};

}
This structure is used to execute a function when the mouse falls over div1, and then this function contains two functions, one is when the mouse moves on the page, and the other is when the mouse leaves the page.
DisX = oEvent. clientX-oDiv.offsetLeft; where Event. clientX is the coordinate of X when the mouse falls. oDiv. offsetLeft is the left margin of div1. The difference between the two values can be used as a reference value. When you move the cursor to the next position, an Event is generated. the clientX value can be used to obtain the oDiv. offsetLeft, that is, the left margin of div1.
DisY = oEvent. clientY-oDiv.offsetTop; Same as above, in order to get the top margin of div1 when the mouse moves to the next position.
Var l = oEvent. clientX-disX; var t = oEvent. clientY-disY; these two values are obtained.


UmentElement. clientHeight is the page height, and oDiv. offsetHeight is the width of div1. When l <0, make l = 0 the left-side control. When l> document.documentelement.clientwidth-odiv.offsetwidth, set l1_document.doc umentElement. clientWidth-oDiv.offsetWidth is the control on the right; when t <0, make t = 0s is the control on the top; when t> document.documentelement.clientheightodiv.offsetheight, make tsf-document.doc umentElement. the clientHeight-oDiv.offsetHeight is under the control.
If (l <0)
{
L = 0;
}
Else if (l> document.doc umentElement. clientWidth-oDiv.offsetWidth)
{
Lw.document.doc umentElement. clientWidth-oDiv.offsetWidth;
}

If (t <0)
{
T = 0;
}
Else if (t> document.doc umentElement. clientHeight-oDiv.offsetHeight)
{
Tsf-document.doc umentElement. clientHeight-oDiv.offsetHeight;
}


Document. onmouseup = function ()
{
Document. onmousemove = null;
Document. onmouseup = null;
};
This function is used to prohibit moving events as soon as the mouse leaves the page.
Return false; block system default behavior.




Example 4: constant speed


CSS style:
<Style>
# Div1 {width: 100px; height: 100px; position: absolute; background: red; left: 0; top: 50px ;}
</Style>


JavaScript code:
<Script type = "text/javascript">
Var timer = null;
Function startMove (iTarget ){
Var oDiv = document. getElementById ('div1 ');

ClearInterval (timer );
Timer = setInterval (function (){
Var iSpeed = 0;

If (oDiv. offsetLeft <iTarget ){
ISpeed = 7;
} Else {
ISpeed =-7;
}

If (Math. abs (oDiv. offsetLeft-iTarget) <7) {// whether to reach the end point
ClearInterval (timer); // reach the destination

ODiv. style. left = iTarget + 'px ';
} Else {
ODiv. style. left = oDiv. offsetLeft + iSpeed + 'px '; // before arriving
}
}, 30 );
}
</Script>


Function startMove (iTarget) {} Where iTarget is a parameter passing, you can see in the html structure onclick = "startMove (300)", here is 300
ClearInterval (timer); clearing time
SetInterval () {function, 30}; interval timer, which executes the timer function every 30 ms, and also uses the delayed Timer: only once, for example, setTimeout (show, 1000 );


If (oDiv. offsetLeft <iTarget ){
ISpeed = 7;
} Else {
ISpeed =-7;
}
This is to judge the relationship between div1 and the target location. If the value is smaller than or equal to the left side, the speed is positive. In this way, the right side can be moved to the target. If the value is greater than the right side, the speed is negative, in this way, the target can be moved to the left.
Math. abs (oDiv. offsetLeft-iTarget) is an integer.
If (Math. abs (oDiv. offsetLeft-iTarget) <7) {// whether to reach the end point
ClearInterval (timer); // reach the destination

ODiv. style. left = iTarget + 'px ';
} Else {
ODiv. style. left = oDiv. offsetLeft + iSpeed + 'px '; // before arriving
This indicates that the timer is cleared when the target location is not reached, and the left margin of div1 is equal to the target location. If the target location is not reached, the timer moves at a constant speed.




Html structure:
<Input type = "button" value = "Start motion" onclick = "startMove (300)"/>




Example 5: Buffer Motion


CSS style:
<Style>
# Div1 {width: 100px; height: 100px; position: absolute; background: red; left: 0px; top: 50px ;}
Span {width: 1px; height: 300px; background: black; position: absolute; left: 300px; top: 0 ;}
</Style>
Span is the label selector, which restricts the elements in the row. Note that there is no semicolon behind the CSS style.






JavaScript code analysis:
<Script type = "text/javascript">
Var timer = null;


Function startMove (iTarget ){
Var oDiv = document. getElementById ('div1 ');

ClearInterval (timer );
Timer = setInterval (function (){
Var iSpeed = (iTarget-oDiv.offsetLeft)/8;
ISpeed = iSpeed> 0? Math. ceil (iSpeed): Math. floor (iSpeed); // when the speed is greater than 0, it is rounded up and the speed is 1 to reach the end point. When the speed is less than 0, it is rounded down to-1 to reach the end point.

If (oDiv. offsetLeft = iTarget) {// whether to reach the end point
ClearInterval (timer); // reach the destination
}
Else {
ODiv. style. left = oDiv. offsetLeft + iSpeed + 'px '; // before arriving
}

Var oTxt = document. getElementById ("txt1 ");
OTxt. value = oDiv. offsetLeft + "," + iSpeed;
}, 30 );
}


</Script>
ISpeed = iSpeed> 0? Math. ceil (iSpeed): Math. floor (iSpeed); this is a judgment structure. Before a colon is actually executed, it is falsely executed after a colon.
Var oTxt = document. getElementById ("txt1"); oTxt. value = oDiv. offsetLeft + "," + iSpeed; the two items will display the speed in the input box.


HTML structure:
<Body>
<Input type = "button" value = "Start motion" onclick = "startMove (300)"/>
<Div id = "div1"> </div>
<Span> </span>
<Input id = "txt1" type = "text"/>
</Body>




Example 6: Hide sub-menu


CSS style:
<Style>
<! --
Body {
Background-color: # ffdee0;
}
# Navigation {
Width: 200px;
Font-family: Arial;
}
# Navigation> ul {
List-style-type: none;/* do not display the project symbol */
Margin: 0px;
Padding: 0px;
}
# Navigation> ul> li {
Border-bottom: 1px solid # ED9F9F;/* Add underline */
}
# Navigation> ul> li> {
Display: block;/* block display */
Padding: 5px 5px 5px 0.5em;
Text-decoration: none;
Border-left: 12px solid #711515;/* rough red edge on the left */
Border-right: 1px solid #711515;/* shadow on the right */
}
# Navigation> ul> li> a: link, # navigation> ul> li> a: visited {
Background-color: # c11136;
Color: # FFFFFF;
}
# Navigation> ul> li> a: hover {/* When the mouse passes */
Background-color: #990020;/* change the background color */
Color: # ffff00;/* change the text color */
}


/* Submenu CSS style */
# Navigation ul li ul {
List-style-type: none;
Margin: 0px;
Padding: 0px 0px 0px 0px;
}
# Navigation ul li {
Border-top: 1px solid # ED9F9F;
}
# Navigation ul li {
Display: block;
Padding: 3px 3px 3px 0.5em;
Text-decoration: none;
Border-left: 28px solid # a71f1f;
Border-right: 1px solid #711515;
}
# Navigation ul li a: link, # navigation ul li a: visited {
Background-color: # e85070;
Color: # FFFFFF;
}
# Navigation ul li a: hover {
Background-color: # c2425d;
Color: # ffff00;
}
# Navigation ul li ul. myHide {/* Hide sub menu */
Display: none;
}
# Navigation ul li ul. myShow {/* show sub menu */
Display: block;
}
-->
</Style>


JavaScript code analysis:
<Script language = "javascript">
Function change (){
// Locate the subnode ul
Var oSecondDiv = this. getElementsByTagName ("ul") [0];
// Alert (oSecondDiv );
// Use CSS to achieve explicit and implicit replacement.
If (oSecondDiv. className = "myHide ")
OSecondDiv. className = "myShow ";
Else
OSecondDiv. className = "myHide ";
}
Window. onload = function (){
Var oUl = document. getElementById ("listUL ");
Var aLi = oUl. childNodes; // sub-element
Var oA;
For (var I = 0; I <aLi. length; I ++ ){
// If the sub-element is li, and this li has sub-menu ul
// Note: The tag name must be in uppercase "LI"
If (aLi [I]. tagName = "LI" & aLi [I]. getElementsByTagName ("ul"). length ){
OA = aLi [I]; // locate the hyperlink
OA. onclick = change; // Add a function dynamically
}
}
}
</Script>
Var oSecondDiv = this. getElementsByTagName ("ul") [0]; getElementsByTagName obtained based on the tag name, represented as an array, the first element in the [0] array.
OSecondDiv. className = "myShow"; className can specify the ccs style.
OUl. childNodes; the sub-element of Ul is Li.


HTML structure:
<Div id = "navigation">
<Ul id = "listUL">
<Li> <a href = "#"> Home </a> </li>
<Li> <a href = "#"> News </a>
<Ul class = "myHide">
<Li> <a href = "#"> Lastest News </a> </li>
<Li> <a href = "#"> All News </a> </li>
</Ul>
</Li>
<Li> <a href = "#"> Sports </a>
<Ul class = "myHide">
<Li> <a href = "#"> Basketball </a> </li>
<Li> <a href = "#"> Football </a> </li>
<Li> <a href = "#"> Volleyball </a> </li>
</Ul>
</Li>
<Li> <a href = "#"> Weather </a>
<Ul class = "myHide">
<Li> <a href = "#"> Today's Weather </a> </li>
<Li> <a href = "#"> Forecast </a> </li>
</Ul>
</Li>
<Li> <a href = "#"> Contact Me </a> </li>
</Ul>
</Div>




Example 7: simple calendar


CSS style:
@ Charset "UTF-8 ";
/* CSS Document */


* {Padding: 0; margin: 0 ;}
Li {list-style: none ;}
Body {background: # f6f9fc; font-family: arial ;}


. Calendar {width: 210px; margin: 0 auto; padding: 10px 10px 20px 20px; background: # eae9e9 ;}
. Calendar ul {width: 210px; overflow: hidden; padding-bottom: 10px ;}
. Calendar li {float: left; width: 58px; height: 54px; margin: 10px 10px 0 0; border: 1px solid # fff; background: #424242; color: # fff; text-align: center; cursor: pointer ;}
. Calendar li h2 {font-size: 20px; padding-top: 5px ;}
. Calendar li p {font-size: 14px ;}


. Calendar. active {border: 1px solid #424242; background: # fff; color: # e84a7e ;}
. Calendar. active h2 {}
. Calendar. active p {font-weight: bold ;}


. Calendar. text {width: 178px; padding: 0 10px 10px; border: 1px solid # fff; padding-top: 10px; background: # f1f1f1; color: #555 ;}
. Calendar. text h2 {font-size: 14px; margin-bottom: 10px ;}
. Calendar. text p {font-size: 12px; line-height: 18px ;}


JavaScript code analysis:
Var aInnerText =
[
"It's coming soon. You can discuss where to play ~ ",
"Proficient in JavaScript development courses-course completion standards-there are 10 standards that can help you become a JS master ...... ",
"Bbs.miaov.com is officially opened. It looks like a forum. It is actually a technology station and is divided into five sections: video tutorials, wonderful life shows, special effects, technical exchanges, and interesting chats ",
"Proficient in various DOM applications, familiar with object-oriented programming ideas (OOP), familiar with JS object-oriented development methods-Wonderful class-www.miaov.com ",
"Proficient in AJAX technology and related applications (such as Sina Weibo-level applications)-miaowei classroom-www.miaov.com ",
"Small Libraries similar to jQuery can be written independently (various selection operators, event classes, DOM, Custom Animation animate, AJAX ......) -Miaov.com ",
"Proficient in JS sports special effects technology, able to fully implement all kinds of website animation special effects, such as the official site of the wonderful class-Wonderful class-www.miaov.com ",
"Master JS debugging and optimization technologies, be compatible with all browsers-wonderful classes-www.miaov.com ",
"Proficient in JS event objects and event working mechanisms, and able to develop various cross-platform application modules-miaowei class-www.miaov.com ",
"RIA applications that provide excellent performance and performance independently-miaov.com-www.miaov.com ",
"Understand background programming knowledge and be able to work with background engineers to complete large-scale interactive applications-miaov.com-www.miaov.com ",
"Familiar with regular expression writing, application, and advanced form verification technology-miaowei class-www.miaov.com"
];


Window. onload = function ()
{
Var oDiv = document. getElementById ('tab ');
Var aLiBtn = oDiv. getElementsByTagName ('ul ') [0]. getElementsByTagName ('lil ');
Var I = 0;

For (I = 0; I <aLiBtn. length; I ++)
{
ALiBtn [I]. onmouseover = select;
}
};


Function select ()
{
Var oDiv = document. getElementById ('tab ');
Var aLiBtn = oDiv. getElementsByTagName ('ul ') [0]. getElementsByTagName ('lil ');
Var oDivContent = oDiv. getElementsByTagName ('div ') [0];
Var sInnterHtml = '';
Var I = 0;

For (I = 0; I <aLiBtn. length; I ++)
{
ALiBtn [I]. className = '';
}

For (I = 0; I <aLiBtn. length; I ++)
{
If (aLiBtn [I] === this) // the serial number of this is I
{
ALiBtn [I]. className = 'active ';

// Modify the lower text
SInnterHtml = "SInnterHtml + = "<p>" + aInnerText [I] + "</p> ";

ODivContent. innerHTML = sInnterHtml;
}
}
}


HTML structure:
<Div id = "tab" class = "calendar">


<Ul>
<Li class = "active"> <Li> <Li> <Li> <Li> <Li> <Li> <Li> <Li> <Li> <Li> <Li> </Ul>

<Div class = "text">
<H2> January event <P> it's coming soon. You can discuss where to play ~ </P>
</Div>


</Div>




Simple calendar learning report
Three-layer structure of the calendar:
In the same way, I used three structures in writing this calendar, which is a common method for Web pages.
Level 1: structure layer, which refers to the (X) html tag. The calendar is put there and displayed with the TAG.
Layer 2: presentation layer. CSS is responsible for displaying the style of the image.
Layer 3: behavior layer, which refers to the behavior created with JAVASCIPT and is responsible for answering "How should the content respond to things"
In short:
(1) Use (X) HTML to build the document structure
(2) Use CSS to set the document Display Effect
(3) Use DOM scripts to implement document Behavior


Http://blog.chinaunix.net/uid-7215926-id-61751.html


Level 1:
Html webpage Structure
Div contains an unordered list containing 12 months, two rows per month, the first row of numbers, and the second row of English.
There is also a div, which is the first month of activity content by default.






Layer 2:
CSS code Display Effect


* Global


Tag name selector
Li
Li {list-style: none;} removes small black spots in front of li
Body




Class Selector
. Calendar


Width, padding-bottom, margin, and border in. calendar ul and. calendar li determine that each row can only be arranged for three months, and each month has a border.


. Calendar. text combo Selector


Layer 3:
Javascript code


First, an array is defined. The array contains 12 elements. The first element corresponds to the activity of the first month.


Run the function when the system is loaded.


Var oDiv = document. getElementById ('tab'); define the target div
Var aLiBtn = oDiv. getElementsByTagName ('ul ') [0]. getElementsByTagName ('lil'); treats every month as a block and makes all monthly blocks an array
For (I = 0; I <aLiBtn. length; I ++)
{
ALiBtn [I]. onmouseover = select;
}
In the for loop, each block corresponds to a sleect function. When you move the cursor over the block, the select function is executed.




The select function is defined below.




Var oDivContent = oDiv. getElementsByTagName ('div ') [0]; this is equivalent to the first div in the div whose id is tab, that is, the div that displays the month activity.


The first for loop mainly corresponds to the monthly block CSS style described above. It is empty here, that is, all the styles are cleared first. The following for loop means that whenever the mouse moves to the specified monthly block, the CSS style of the monthly block is active.


Then the content is displayed. The content is superimposed. the previously defined content array elements are also used. Finally, the content is added to the webpage using. innerHTMl.




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.