1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <link rel="stylesheet" href="左边选项卡/css/bootstrap.min.css"/> 7 8 <style> 9 *{ 10 padding: 0; 11 margin: 0; 12 } 13 #main{ 14 width: 400px; 15 height: 400px; 16 position: absolute; 17 top: 10px; 18 left: 0; 19 border: 1px solid #ccc; 20 border-radius: 5px; 21 background: #e6ecf8; 22 } 23 h3{ 24 margin: 0; 25 width: 399px; 26 height: 40px; 27 background: #e6b60e; 28 cursor: pointer; 29 line-height: 40px; 30 border-radius: 5px 5px 0 0; 31 } 32 </style> 33 </head> 34 <body> 35 <div id="main"> 36 <h3>拖动</h3> 37 <div id="container">可拖动的层</div> 38 </div> 39 </body> 40 <script src="js/jquery.min.js"></script> 41 <script> 42 $(function(){ 43 //一个jQuery的鼠标拖动插件函数,参数为要拖动的对象 44 $.fn.extend({SliderObject:function(objMoved){ 45 var mouseDownPosiX; 46 var mouseDownPosiY; 47 var InitPositionX; 48 var InitPositionY; 49 var obj = $(objMoved) == undefined ? $(this) : $(objMoved); 50 $(this).mousedown(function(e){ 51 //当鼠标按下时捕获鼠标位置以及对象的当前位置 52 mouseDownPosiX = e.pageX; 53 mouseDownPosiY = e.pageY; 54 55 InitPositionX = obj.css("left").replace("px",""); 56 InitPositionY = obj.css("top").replace("px",""); 57 obj.mousemove(function(e){ //obj.mousemove(function(e){ 这里可以改成$(document).mousemove可以避免鼠标移动太快而失去焦点的问题 58 var tempX = parseInt(e.pageX) - parseInt(mouseDownPosiX) + parseInt(InitPositionX); 59 var tempY = parseInt(e.pageY) - parseInt(mouseDownPosiY) + parseInt(InitPositionY); 60 obj.css("left",tempX+"px").css("top",tempY + "px"); 61 }).mouseup(function(){//当鼠标弹起活着离开元素时,将鼠标弹起设置为false,不移动对象 62 obj.unbind("mousemove"); 63 }).mouseleave(function(){ 64 obj.unbind("mousemove"); 65 }); 66 }) 67 } 68 }); 69 $(document).ready(function(){ 70 $("h3").SliderObject($("#main")); 71 }) 72 }) 73 </script> 74 </html>
时间: 2024-10-09 07:59:54