The main use of two functions
parseint ()
SUBSTR ()
First get the ID of the element
var j = document.getElementById ("ID");
Then get the Location property
var top = j.style.top// here to control the position of the element up and down, control the left and right of the words to change the top
It should be noted that using this method requires that the element to be moved be set to absolute positioning, and the style is added position:absolute;
Now the position of the element is moved, because the element used to get the method should be ("0px") a string string type, and we need to convert it to number. and remove the back "px";
J=parseint (J.substr (0,j.length-2));
The last simple addition and subtraction
J.style.top= (j+10) + "px"; // The Top property increases and the position moves down
Attach a chunk of code reference
<Head><MetaCharSet= "Utf-8"> <Scripttype= "Text/javascript"src= "2.js"></Script> <Script> functionMove (Fangxiang) {varper=document.getElementById ("cc"); varJ=Per.style.top; vark=Per.style.left; J=parseint (J.substr (0, J.length-2)); K=parseint (K.substr (0, K.length-2)); Switch(Fangxiang) { Case 1: Per.style.top=(J-Ten)+"px"; Break; Case 2: Per.style.top=(J+Ten)+"px"; Break; Case 3: Per.style.left=(k-Ten)+"px"; Break; Case 4: Per.style.left=(k+Ten)+"px"; Break; } } </Script></Head><Body><Divstyle= "Width:500;height:500;background-color:pink"> <Divstyle= "background-color:blue;width:50;height:50;position:absolute;left:40px;top:40px"ID= "CC"></Div></Div><Buttonstyle= "margin-left:30px;"onclick= "Move (1)">W</Button><BR><Buttononclick= "Move (3)">A</Button><Buttononclick= "Move (2)">S</Button><Buttononclick= "Move (4)">D</Button><BR></Body>
stringobject. substr (start,length)
| Parameters |
Description |
| Start |
Necessary. The starting subscript for the substring to extract. Must be numeric. If it is a negative number, the argument declares the position from the end of the string. That is,-1 refers to the last character in the string, 2 refers to the second-lowest character, and so on. |
| Length |
Optional. The number of characters in the substring. Must be numeric. If this argument is omitted, then the string from the beginning of the Stringobject to the end is returned.
|
Use JS to control page element position movement