1234567891011121314151617181920212223242526272829303132333435363738394041 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- #box{
- width: 100px;
- height: 100px;
- background-color: red;
- position: absolute;
- }
- </style>
- </head>
- <body>
- <div id="box"></div>
- <script>
- // 第一步获取元素 正方形
- var oBox = document.getElementById("box");
- // 获取页面
- var oPage = document.documentElement;
- // 第二步给元素添加事件 给正方形绑定鼠标按下事件
- oBox.onmousedown = function(e){
- // 记录鼠标点击时在正方形的哪个位置
- var x = e.offsetX;
- var y = e.offsetY;
- // 第三步给页面绑定移动事件
- oPage.onmousemove = function(e){
- oBox.style.top = (e.clientY - y)+ "px";
- oBox.style.left = (e.clientX - x )+ "px";
- }
- }
- // 第四步移除页面移动事件
- oBox.onmouseup = function(){
- oPage.onmousemove = null;
- }
- </script>
- </body>
- </html>
|