最简洁的js鼠标拖曳效果【原】

请原谅我是一个标题档,不过还是很简洁的,因为只是初步的实现的拖曳效果
复制代码
<!DOCTYPE html>
<html>
<head>
    
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
<meta http-equiv="Content-Language" content="zh-cn" />
    
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
    
<title>DragDrop</title>
    
<meta name="author" content="flowerszhong">
    
<meta name="date" content="">
    
<link href="" rel="stylesheet" type="text/css" />
    
<!--[if IE]>
      <script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
  <![endif]
-->
    
<!-- <script src="http://code.jquery.com/jquery-latest.js"></script> -->
    
<style type="text/css">
        .redBorderBox
        
{
            border
: 2px solid red;
            position
: absolute;
            width
: 60px;
            height
: 60px;
            cursor
: move;
            background-color
: Red;
        
}
    
</style>
</head>
<body>
    
<div id="hd">
    
</div>
    
<div id="bd">
        
<div class="redBorderBox" id="dragObj1">
            i am not dragObj
</div>
        
<div class="redBorderBox dragObj" id="dragObj2" style="top: 90px; left: 90px;">
            u can drag me
</div>
    
</div>
    
<div id="ft">
    
</div>
</body>

<script>
    
/* 鼠标拖动 */
    (
function() {
        
var oDrag = "";
        
var ox, oy, nx, ny, dy, dx;
        
function drag(e) {
            
var e = e ? e : event;
            oDrag 
= e.target ? e.target : e.srcElement;
            
if (oDrag.className.indexOf("dragObj"== -1) { oDrag = ""}
            ox 
= e.clientX;
            oy 
= e.clientY;
        }
        
function dragPro(e) {
            
if (oDrag != "") {
                
var e = e ? e : event;
                dx 
= parseInt(oDrag.style.left);
                dy 
= parseInt(oDrag.style.top);
                nx 
= e.clientX;
                ny 
= e.clientY;
                oDrag.style.left 
= (dx + (nx - ox)) + "px";
                oDrag.style.top 
= (dy + (ny - oy)) + "px";
                ox 
= nx;
                oy 
= ny;
            }
        }
        document.onmousedown 
= function(e) { drag(e); }
        document.onmouseup 
= function() { oDrag = ""; }
        document.onmousemove 
= function(event) { dragPro(event); }
    })();
</script>

</html>
复制代码
感谢你留言,转载请声明出处:http://www.cnblogs.com/flowerszhong
posted @   码不能停  阅读(1515)  评论(2编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示