1 <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 3 <html xmlns="http://www.w3.org/1999/xhtml"> 4 <head> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 6 <title>拖动DIV</title> 7 8 <style type="text/css"> 9 .show{ 10 background:#7cd2f8; 11 width:100px; 12 height:100px; 13 text-align:center; 14 position:absolute; 15 z-index:1; 16 left:100px; 17 top:100px; 18 } 19 </style> 20 21 <script type="text/javascript" src="http://sandbox.runjs.cn/uploads/rs/165/x9ajweu6/1.5_jquery.min.js"></script> 22 <script type="text/javascript"> 23 $(document).ready(function(){ 24 $(".show").mousedown(function(e){ //e鼠标事件 25 $(this).css("cursor","move");//改变鼠标指针的形状 26 27 var offset = $(this).offset();//DIV在页面的位置 28 var x = e.pageX - offset.left;//获得鼠标指针离DIV元素左边界的距离 29 var y = e.pageY - offset.top;//获得鼠标指针离DIV元素上边界的距离 30 $(document).bind("mousemove",function(ev){ //绑定鼠标的移动事件,因为光标在DIV元素外面也要有效果,所以要用doucment的事件,而不用DIV元素的事件 31 $(".show").stop();//加上这个之后 32 33 var _x = ev.pageX - x;//获得X轴方向移动的值 34 var _y = ev.pageY - y;//获得Y轴方向移动的值 35 36 $(".show").animate({left:_x+"px",top:_y+"px"},10); 37 }); 38 }); 39 40 $(document).mouseup(function(){ 41 $(".show").css("cursor","default"); 42 $(this).unbind("mousemove"); 43 }); 44 }); 45 </script> 46 </head> 47 <body> 48 <div class="show"> 49 jquery实现DIV层拖动 50 </div> 51 </body> 52 </html>
时间: 2024-10-18 17:10:38