练习案例_可拖动的div层
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>可拖动的div层</title> <style type="text/css"> .draggable-div{ position: absolute; width: 300px; height:185px; background-color: lightgray; } </style> <script type="text/javascript" src="jquery-1.8.3.js"></script> <script type="text/javascript"> var draggable = false; var offsetX = 0;//按下鼠标按键的时候,当前鼠标的x坐标和div左上角定点的x坐标的差值 var offsetY = 0; $(document).ready(function(){ $("#draggableDiv").css("position","absolute").mousedown(function () { draggable = true; offsetX = event.clientX-this.offsetLeft; offsetY = event.clientY-this.offsetTop; }).mouseup(function () { draggable = false; }).mousemove(function () { //如果draggable为true,改变div的位置 if(draggable){ this.style.left = event.clientX-offsetX+"px"; this.style.top = event.clientY-offsetY+"px"; } }).mouseout(function(){ draggable=false; }); }); </script> </head> <body> <div id="draggableDiv" class="draggable-div"></div> </body> </html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title></title> <script type="text/javascript"> var draggable = false; //鼠标指针y坐标的减去div左上角顶点y坐标 var offsetY = 0; var offsetX = 0; window.onload=function(){ var div01 = document.getElementById("div01"); div01.style.position = "absolute"; div01.onmousedown=function(){ draggable = true; offsetY = event.clientY - div01.offsetTop; offsetX = event.clientX - div01.offsetLeft; } div01.onmouseup=function(){ draggable=false; } div01.onmousemove=function(){ if(draggable){ //拖动 this.style.left = event.clientX-offsetX+"px"; this.style.top = event.clientY - offsetY+"px"; } } div01.onmouseout=function(){ draggable = false; } } </script> </head> <body> <div id="div01" style="width: 300px;height: 185px;background-color: lightgray"></div> </body> </html>