使用JS实现可移动的Div

algorain

使用JS实现可移动的Div

这是老师上课要求做的,使用JS实现div的移动,其实就是获取鼠标和div的位置,然后进行修改,代码如下。想要试用一下的效果的,可以看最下面,我把HTML代码直接放到md文档中,应该可以直接编译。

直接放到md中,整个页面就乱了,我还是新开一个页,想调试的可以戳这里www.rain1024.com-js75.html

下面是代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
var oldLeft,oldMouseLeft;
var oldRight,oldMouseRight;
var isDown=false;
function mousedown(e){
oldLeft=document.getElementById('div1').style.left;
oldMouseLeft= e.clientX;
oldRight=document.getElementById('div1').style.top;
oldMouseRight= e.clientY;
isDown = true;
}
function mousemove(e){
if(isDown){
var newMouseLeft= e.clientX;
var newLeft=parseInt(oldLeft)+parseInt(newMouseLeft)-parseInt(oldMouseLeft)+"px";
var newMouseRight= e.clientY;
var newRight=parseInt(oldRight)+parseInt(newMouseRight)-parseInt(oldMouseRight)+"px";
document.getElementById('div1').style.left=newLeft;
document.getElementById('div1').style.top=newRight;
}
}
function mouseup(){
isDown=false;
}
</script></head>
<body>
<div id="div1" style="background-color: blue;position: absolute;left: 100px;top: 100px;width: 100px;height: 100px"
onmousedown="mousedown(event)" onmousemove="mousemove(event)"
onmouseup="mouseup()">
</div>
<!--onmousedown="getXY(event);"-->
</body>
</html>
  • Title: 使用JS实现可移动的Div
  • Author: algorain
  • Created at: 2017-04-30 14:56:17
  • Updated at: 2023-05-14 21:39:50
  • Link: http://www.rain1024.com/2017/04/30/js-article75/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments