Web page make foreground JavaScript mouse event

Source: Internet
Author: User
Tags abs bind contains copy expression variables variable window
javascript| Mouse | Web page

If you don't understand it, expect 1-2 weeks to finish it .... Do not look too carefully, and then see the back when you do not know how to look at these things better.

1. Foreword and preparatory work

There is no introduction to the use of software in a class of things. If you think the handwriting code is in the pretending person can go out, thank you.

First you have to have a computer. Then it should be loaded with Windows and IE. The following code is only debugged under IE6.0, but I'll try to use the standard notation. This is a different tutorial, not to be careful about compatibility issues. I'm used to editing with Notepad or ultraedit, and virtually any text editor is OK, as long as you like it. How to use these tools will not say, we speed up.

2. The first example

What do you do well? Let's start with the simplest .... Give yourself a special effect to play? ... Let me think about .... How about a square that can be thrown? began to do ...

2.1 Square

Run Code Box

<div style= "width:140px; height:140px; background-color:orange; cursor:pointer;" ></div>
Run code Copy Code Save Code Collect this page

Do not say that I am perfunctory ah, everything has a very simple beginning, just like I was kicked out of my front mm ...
PS: A careful friend may find that my cursor is using pointer instead of hand, because the hand attribute does not conform to the standard. Although I only write code for IE, it is necessary to keep good habits. In the future, all such problems will be marked with "(concurrently)".

2.2 can drag the square

2.21 bound mouse events: pressing, dragging, releasing; Getting event information: position, occurrence of element

Run Code Box

<textarea id="code1"><div style= "width:140px height:140px; background-color:pink cursor:pointer;" id= "Divblock" >I am a div.< /div><script>function Divblock_event_mousedown () {document.onmousemove=document_event_mousemove; var i_do_not_care=document.attachevent?document.attachevent ("OnMouseUp", Document_event_mouseup): Document.addeventlistener ("MouseUp", Document_event_mouseup, "");} function Document_event_mousemove (e) {var e, obj; Obj=document.getelementbyid ("Divblock"); e=window.event?window.event:e;obj.firstchild.nodevalue=e.clientx+ ":" +e.clienty;} function Document_event_mouseup (e) {document.onmousemove= ""; var i_do_not_care=document.detachevent? Document.detachevent ("onmouseup", Document_event_mouseup):d ocument.removeeventlistener ("MouseUp", document_event _mouseup, "");} </script></textarea>
Run codeCopy CodeSave CodeCollect this page

For the rookie, this code actually contains a lot of content.

Name of 2.210 variable
This is a very important thing, and I have to put the phrase number 2.210 to remind the novice beginner-to name your variables in a way that you can understand. If you're going to make a living, it's best to have your variable name read by others.

2.211 Binding Event-four ways to return words
(a) writes directly to the HTML element tag:
(b) Assign the handle of the event function to the corresponding event: Document.onmousemove=document_event_mousemove; (Note that the value of the function name is not followed by parentheses)
c) using the Attachevent method (is AddEventListener for the FF class browser)
PS: Unbind the event also has a corresponding way, not wordy

2.212 Don't be that i_do_not_care=. What the confusion, that is ternary expression, if you have to seriously learn the JS grammar. The purpose of that writing is compatible.

2.213 It is a good habit to declare variables that need to be used at the front of the function body, and it can prevent you from making a lot of inexplicable mistakes-like recursive dead loops. Of course, if you don't like the variable at all (like my i_do_not_care), then just let it go.

2.214 e=window.event?window.event:e; Also for compatibility. In fact, this sentence is only to get the event object. Using E.clientx without e.x is also a compatibility issue. Obj.firstChild.nodeValue rather than obj.innertext. <div>i am a div.</div> and not <div></div> is the same. -Compatibility is a tnnd problem.

2.215 If you find yourself still a little confused, go back and review the sections of the events mentioned in sections 0.1 and 0.2

2.22 Drag Square

Run Code Box

<div style= "width:140px; height:140px; Background-color:pink; Cursor:pointer "id=" Divblock "></div><script>function Divblock_event_mousedown (e) {var e, obj, temp; Obj=document.getelementbyid ("Divblock"); E=window.event?window.event:e; Obj.startx=e.clientx-obj.offsetleft; Obj.starty=e.clienty-obj.offsettop; Document.onmousemove=document_event_mousemove; Temp=document.attachevent?document.attachevent ("onmouseup", Document_event_mouseup):d Ocument.addeventlistener (" MouseUp ", Document_event_mouseup," ");} function Document_event_mousemove (e) {var e, obj; Obj=document.getelementbyid ("Divblock"); E=window.event?window.event:e; With (Obj.style) {position= "absolute"; left=e.clientx-obj.startx+ "px"; top=e.clienty-obj.starty+ "px"; }}function Document_event_mouseup (e) {var temp; document.onmousemove= ""; Temp=document.detachevent? Document.detachevent ("onmouseup", Document_event_mouseup):d ocument.removeeventlistener ("MouseUp", document_event _mouseup, "");} </script&Gt
Run codeCopy CodeSave CodeCollect this page

2.221 Programming is a mental activity, hehe. First you have to figure out what it means to drag. In fact, drag is to judge the location of the mouse, and then change the elements you need to drag the coordinates just. Then split into two steps: judge the mouse position and change the coordinates of the element. This does not look too difficult. The previous point 2.21 just discussed. After a bit, if you have a knowledge of JS operation CSS is also easy (not clear back to see section 0.3).

2.222 Now I describe this process in detail:
A when the mouse is pressed, judge the position of the mouse. The difference between the mouse coordinates and the element coordinates exists in the STARTX and Starty two custom properties of the element. Bind mouse Move events.
b When the mouse moves, judge the position of the mouse. The difference between the mouse coordinates and the startx/starty is used as the new element coordinate. (Why do you ask me?) Handsome boy please go back to retake high school mathematics, hehe
c) mouse button lift, clear the corresponding mouse movement events. (Otherwise you let go of the mouse box or follow you to run)

Why 2.223 Use document events to bind rather than bind events to Div? That's a good question, don't you think? ... If you try to bind the event to the Div, you will find that with the rapid movement of the mouse, it is easy to get rid of the div (do not understand the classmate please do their own hands). The specific why not say more, point to stop, I hope the rookie think more.

2.224 does not define position= "absolute", left and top are invalid-the box does not move to say.

2.3 can move the square

2.31 physical model and object oriented

Run Code Box

<div style= "width:140px height:140px; background-color:pink; Cursor:pointer" id= "Divblock" ></div> <script>f=0.95; Motion damping k=0.85; Collision elasticity coefficient g=1; Gravitational acceleration window.onload=init;function init () {var obj; Obj=document.getelementbyid ("Divblock"); Obj.speedx=parseint (Math.random () *5); Obj.speedy=parseint (Math.random () *5); Obj.move=function () {//Here I temporarily do not write, hehe}}</script>
Run code Copy Code Save Code Collect this page

2.311
The model is simple:
Properties of the object: velocity (contains the X component and the Y component, which is set to a random number of 0-5)
The method of the object: Motion
Ambient properties: Motion damping F, and window edge collision elasticity coefficient k, gravitational acceleration g

2.312 Note obj.move The method (function)

2.32 Let the cube move.

Run Code Box

<div style= "width:140px; height:140px; Background-color:pink; Cursor:pointer; Position:absolute "id=" Divblock "></div><script>f=0.005; Motion damping k=0.7; Collision elasticity coefficient g=1; Gravity acceleration var obj;window.onload=init;function init () {Obj=document.getelementbyid ("Divblock"); obj.speedx=140; obj.speedy=400; Obj.move=function () {var x, y, mx, my; X=this.offsetleft; Y=this.offsettop; Mx=document.body.clientwidth-this.offsetwidth; Calculating the maximum range of allowable motion my=document.body.clientheight-this.offsetheight; this.speedy+=g; The y-direction velocity this.speedx-=f*this.speedx*this.speedx* (this.speedx>0?1:-1) for calculating the effect of gravitational acceleration; The Velocity this.speedy-=f*this.speedy*this.speedy* (this.speedy>0?1:-1) After the damping is calculated; Damping size and velocity squared are proportional to if (Math.Abs (this.speedx) >mx| | Math.Abs (this.speedy) >my) {this.speedx=this.speedx%mx; this.speedy=this.speedy%my;} X+=this.speedx; Y+=this.speedy; Compute the coordinates if (x<0) {x=-x; This.speedx=math.abs (This.speedx) *k;}//Compute boundary Collision if (y<0) {y=-y; This.speedy=math.abs (this . SpeedY) *k; } if (x>mx) {x=mx*2-x; This.speedx=-math.abs (This.speedx) *k;} if (y>my) {y=my*2-y; This.speedy=-math.abs (This.speedy) *k;} if (Math.Abs (This.speedx) <1) this.speedx=0; Eliminate data underflow if (Math.Abs (my-y) <4&&math.abs (this.speedy) <4) {y=my; this.speedy=0;}//Eliminate Jitter This.style for critical state. Left=parseint (x) + "px"; Realize mobile This.style.top=parseint (y) + "px"; } setinterval ("Obj.move ();", 10);} </script>
Run codeCopy CodeSave CodeCollect this page

The code began to become difficult ah, hehe. Please read the notes carefully.

2.321 is simply an algorithmic expression of a physical process. The implementation of the move is similar to the drag in the previous 2.22 sections.

2.322 Notice the use of this in the code here. When I use this in Obj.move, this refers to OBJ.

2.323 Notice I put Obj outside the function. At this point it is a global variable. This is for the later use of setinterval. A lot of rookie in the timer when often found in the "Object Not found" error, please note that the definition of variable domain problems.

2.324 Rookie. Learn how to do Math with built-in objects

2.33 let the cube stop.

Run Code Box

<div style= "width:140px; height:140px; Background-color:pink; Cursor:pointer; Position:absolute "id=" Divblock "></div><script>f=0.005; Motion damping k=0.7; Collision elasticity coefficient g=1; Gravity acceleration var obj, timehandle;window.onload=init;function init () {Obj=document.getelementbyid ("Divblock"); obj.speedx=140; obj.speedy=400; Obj.move=function () {var x, y, mx, my; X=this.offsetleft; Y=this.offsettop; Mx=document.body.clientwidth-this.offsetwidth; Calculating the maximum range of allowable motion my=document.body.clientheight-this.offsetheight; this.speedy+=g; The y-direction velocity this.speedx-=f*this.speedx*this.speedx* (this.speedx>0?1:-1) for calculating the effect of gravitational acceleration; The Velocity this.speedy-=f*this.speedy*this.speedy* (this.speedy>0?1:-1) After the damping is calculated; Damping size and velocity squared are proportional to if (Math.Abs (this.speedx) >mx| | Math.Abs (this.speedy) >my) {this.speedx=this.speedx%mx; this.speedy=this.speedy%my;} X+=this.speedx; Y+=this.speedy; Compute the coordinates if (x<0) {x=-x; This.speedx=math.abs (This.speedx) *k;}//Compute boundary Collision if (y<0) {y=-y; This.speedy=math.abs (this . sPeedY) *k; } if (x>mx) {x=mx*2-x; This.speedx=-math.abs (This.speedx) *k;} if (y>my) {y=my*2-y; This.speedy=-math.abs (This.speedy) *k;} if (Math.Abs (This.speedx) <1) this.speedx=0; Eliminate data underflow if (Math.Abs (my-y) <4&&math.abs (this.speedy) <4) {y=my; this.speedy=0;}//Eliminate Jitter This.style for critical state. Left=parseint (x) + "px"; Realize mobile This.style.top=parseint (y) + "px"; This.timehandle=settimeout ("Obj.move ();", 10); } obj.stop=function () {cleartimeout (this.timehandle); } obj.onmousedown=function () {this.stop ();} Obj.onmouseup=function () {this.move ();} Obj.move ();} </script>
Run codeCopy CodeSave CodeCollect this page

Press the mouse on the box, it will stop, play the mouse, it will continue to run, hehe.

2.331 No one notices the 2.211 binding event-The four ways of writing back words only cite three ways to bind events? Oh, here is the fourth kind:
Obj.onmousedown=function () {this.stop ();}

2.332 I changed the setinterval to settimeout and kept the timer's handle in the attribute of obj. This use of the timer is worth the rookie reference.

2.4 Big Finale-can throw the squares

Run Code Box

<div style= "width:140px; height:140px; Background-color:pink; Cursor:pointer; Position:absolute "id=" Divblock "></div><script>f=0.003; Motion damping k=0.8; Collision elasticity coefficient g=0.6; Gravity acceleration var obj, timehandle;window.onload=init;function init () {Obj=document.getelementbyid ("Divblock"); obj.speedx=0; obj.speedy=0; Obj.lastx=obj.offsetleft; Obj.lasty=obj.offsettop; Obj.move=function () {this.stop (); var x, y, mx, my; X=this.offsetleft; Y=this.offsettop; Mx=document.body.clientwidth-this.offsetwidth; Calculating the maximum range of allowable motion my=document.body.clientheight-this.offsetheight; this.speedy+=g; The y-direction velocity this.speedx-=f*this.speedx*this.speedx* (this.speedx>0?1:-1) for calculating the effect of gravitational acceleration; The Velocity this.speedy-=f*this.speedy*this.speedy* (this.speedy>0?1:-1) After the damping is calculated; Damping size and velocity squared are proportional to if (Math.Abs (this.speedx) >mx| | Math.Abs (this.speedy) >my) {this.speedx=this.speedx%mx; this.speedy=this.speedy%my;} X+=this.speedx; Y+=this.speedy; Computes the coordinate if (x<0) {x=-x; This.speedx=math.abs (This.speEdX) *k; //COMPUTE Boundary Collision if (y<0) {y=-y; This.speedy=math.abs (This.speedy) *k;} if (x>mx) {x=mx*2-x; This.speedx=-math.abs (This.speedx) *k;} if (y>my) {y=my*2-y; This.speedy=-math.abs (This.speedy) *k;} if (Math.Abs (This.speedx) <1) this.speedx=0; Eliminate data underflow if (Math.Abs (my-y) <4&&math.abs (this.speedy) <4) {y=my; this.speedy=0;}//Eliminate Jitter This.style for critical state. Left=parseint (x) + "px"; Realize mobile This.style.top=parseint (y) + "px"; This.timehandle=settimeout ("Obj.move ();", 10); } obj.stop=function () {cleartimeout (this.timehandle); } obj.onmousedown=function () {this.stop (); Divblock_event_mousedown (Arguments[0]);} Obj.move ();} function Divblock_event_mousedown (e) {var e, temp; E=window.event?window.event:e; Obj.startx=e.clientx-obj.offsetleft; Obj.starty=e.clienty-obj.offsettop; Document.onmousemove=document_event_mousemove; Temp=document.attachevent?document.attachevent ("onmouseup", Document_event_mouseup):d Ocument.addeventlistener (" MouseUp ", Document_event_mOuseup, "");} function Document_event_mousemove (e) {var e; E=window.event?window.event:e; With (Obj.style) {position= "absolute"; left=e.clientx-obj.startx+ "px"; top=e.clienty-obj.starty+ "px"; } obj.speedx= (OBJ.OFFSETLEFT-OBJ.LASTX) *3; Obj.speedy= (obj.offsettop-obj.lasty) *3; Obj.lastx=obj.offsetleft; Obj.lasty=obj.offsettop;} function Document_event_mouseup (e) {var temp; document.onmousemove= ""; Temp=document.detachevent? Document.detachevent ("onmouseup", Document_event_mouseup):d ocument.removeeventlistener ("MouseUp", document_event _mouseup, ""); Obj.move ();} </script>
Run codeCopy CodeSave CodeCollect this page

Use the mouse to hold the box, and then move the mouse, and then release the mouse, see the effect bar, hehe

This is the end of the example, haha. Do not explain, you see yourselves.



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.