Drag effect
Html
<!DOCTYPE HTML><HTML> <Head> <MetaCharSet= "Utf-8"> <title> Drag effect </title> <Linkrel= "stylesheet"type= "Text/css"href= "drag effect. css"> </Head> <Body> <DivID= "box"> <H1ID= "Heading">Click to drag</H1> </Div> <Scriptsrc= "drag effect. js"></Script> </Body></HTML>
Css
#box{width:300px;Height:300px;Background-color:Red;padding:10px;Border:5px Solid Green;text-align:Center;position:Absolute;Top:50px; Left:50px;}#heading{Background-color:Blue;}
Javascript
//Call the Drag function after the page has finished loadingWindow.onload =drag;//encapsulating the Drag functionfunctiondrag () {//Get heading element varHeading = document.getElementById ("heading"); //the Fndown function is executed when the mouse is pressed in the heading element areaHeading.onmousedown =Fndown; //Remove the drag effect when the mouse is released in the pageDocument.onmouseup =function() {Document.onmousemove=NULL; };};//encapsulating the Fndown functionfunctionFndown (Event) {event= Event | |window.event; varbox = document.getElementById ("box"), heading= document.getElementById ("heading"), //The distance between the point of the mouse click and the upper left corner of the boxDisy = Event.clienty-Box.offsettop, Disx= Event.clientx-Box.offsetleft; //perform anonymous functions when the mouse moves through the pageDocument.onmousemove =function(Event) {event= Event | |window.event; //The core idea is: Where's the mouse, where's the box? //calculate the distance of the box from the upper-left corner of the page vart = event.clienty-Disy, L= Event.clientx-Disx, Window_width= Document.documentElement.clientWidth | |Document.body.clientWidth, Window_height= Document.documentElement.clientHeight | |Document.body.clientHeight, max_t= Window_height-Box.offsetheight, max_l= Window_width-Box.offsetwidth; //maximum minimum distance to control box movement if(T < 0) {T= 0; } Else if(T >max_t) {T=max_t; }; if(L < 0) {L= 0; } Else if(L >max_l) {L=max_l; }; //the position of the box follows the mouse cursorBox.style.top = t + "px"; Box.style.left= L + "px"; };};
JS Mouse Event Exercise-drag effect