博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

兼容各主流浏览器的简单拖拽drag

Posted on 2009-09-24 10:26  周末  阅读(424)  评论(2编辑  收藏  举报

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>

<style type='text/css'> 
#d
{border:1px solid green;width:90px;height:57px;position:absolute;} 
#h
{border:1px solid green;width:90px;height:17px;position:absolute;} 
</style> 
<script type='text/javascript' src="/js/jquery/jquery-1.2.6.min.js"></script>
<script type='text/javascript'> 
(
function($) {
    $.fn.extend({
        drag: 
function(id) {
            $(
this).mousedown(function(event) {
                
var Obj, pX,pY;
                document.onmouseup 
= MUp;
                document.onmousemove 
= MMove;
                MDown(id, event);
                
function MDown(id, event) {
                    Obj 
= document.getElementById(id);
                    
if (Obj.setCapture) 
                        Obj.setCapture();
                    
else 
                        window.captureEvents(Event.MOUSEMOVE 
| Event.MOUSEUP);
                    pX 
= event.clientX - Obj.offsetLeft;
                    pY 
= event.clientY - Obj.offsetTop;
                }
                
function MMove(event) {
                    
if (window.event) event = window.event;
                    
if (Obj) {
                        Obj.style.left 
= event.clientX - pX + "px";
                        Obj.style.top 
= event.clientY - pY + "px";
                    }
                }
                
function MUp(event) {
                    
if (Obj) {
                        
if (Obj.releaseCapture)
                                Obj.releaseCapture();
                        
else 
                            window.captureEvents(Event.MOUSEMOVE 
| Event.MOUSEUP);
                        Obj 
= null;
                    }
                }
            });
        }
    });
})(jQuery); 

</script> 
</head> 
<body> 
<div id="d"> 
<div id="h">Header</div> 
</div> 

<script type='text/javascript' > 
$(
"#h").drag('d'); //IE下,点击id='h'可拖动id='d',FF兼容待完善 
</script> 
</body>
</html>