直接上代码:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <style type="text/css"> #myMessageDiv { position:absolute; left:100px; top:100px; 500px; height: 400px; border: 2px solid #C0C0C0; background-image: url("images/tmbg.png"); } </style> </head> <body> <form id="form1" runat="server"> <div id="myMessageDiv"> </div> </form> </body> </html> <script type="text/javascript"> //====================================div-move-start=================================== var moving = 0; var _x, _y; $("#myMessageDiv").mousedown(function () { //debugger; this.setCapture(); moving = 1; //开始移动标识 _x = event.clientX; _y = event.clientY; //记录鼠标当前位置 }); $("#myMessageDiv").mouseup(function () { this.releaseCapture(); moving = 0; }); $("#myMessageDiv").mousemove(function () { if (moving == 1) { //debugger; //获取鼠标移动中的位置 var x = event.clientX; var y = event.clientY; //为窗体赋新位置 var X0 = parseInt($("#myMessageDiv").css("left")); var Y0 = parseInt($("#myMessageDiv").css("top")); $("#myMessageDiv").css("top", (Y0 + y - _y)); $("#myMessageDiv").css("left", (X0 + x - _x)); _x = x; _y = y; } }); //====================================div-move-stop=================================== </script>
拖动js并不复杂
关键是通过它来认识setCapture(),releaseCapture()这两个函数,将他们去掉程序仍然能够运行,但是存在bug,有兴趣的朋友可以试试!
Javascript 鼠标捕获
鼠标捕获(setCapture)作用是将鼠标事件捕获到当前文档的指定的对象。这个对象会为当前应用程序或整个系统接收所有鼠标事件。