zoukankan      html  css  js  c++  java
  • 简单实现可拖动div

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Pragma" content="no-cache">
    
    <meta http-equiv="Cache-Control" content="no-cache">
    
    <meta http-equiv="Expires" content="0">
    
    <head>
    <script>
    window.onload=function(){
    var d=document.getElementById('div1');
    if(document.addEventListener) 
    {
    document.addEventListener("mousemove",moveHandler,true);
    document.addEventListener("mouseup",upHandler,true); 
    }
    else
    {
    document.attachEvent("onmousemove",moveHandler);
    document.attachEvent("onmouseup",upHandler); 
    
    }
    d.onmouseup=addE;
    function moveHandler(e)
    {
    if (!e) e=window.event;
    d.style.left=e.clientX+'px';
    d.style.top=e.clientY+'px';
    }
    function upHandler(e) 
    { 
    if(document.removeEventListener) 
    { 
    document.removeEventListener("mouseup",upHandler,true); 
    document.removeEventListener("mousemove",moveHandler,true); 
    } 
    else 
    { 
    document.detachEvent("onmouseup",upHandler); 
    document.detachEvent("onmousemove",moveHandler); 
    }
    if(e.stopPropagation) e.stopPropagation(); 
    else e.cancelBubble=true; 
    }
    
    function addE()
    {
    if(document.addEventListener) 
    {
    document.addEventListener("mousemove",moveHandler,true);
    document.addEventListener("mouseup",upHandler,true); 
    }
    else
    {
    document.attachEvent("onmousemove",moveHandler);
    document.attachEvent("onmouseup",upHandler); 
    
    }
    }
    }
    </script>
    </head>
    <body>
    <div id='div1'  style='left:80px;top:100px;position:absolute;80px;background:#aaaaaa;'>here!</div>
    
    
    </body>
    </html>


    主要利用了mousemove和mouseup事件。当然,还要注意事件处理的方式,这里禁用了冒泡。

    mousemove:鼠标每移动一个像素,就会触发一次事件。

  • 相关阅读:
    2016中国大学生程序设计竞赛
    POJ 2239 化二分图右集合二维为一位的最大匹配
    POJ 1274 二分图最大匹配简单单向
    二分图最大匹配模板
    找割点和割边
    HDU 4432 求因子+进制转换
    HDU 4438 概率 多个情况下的数学期望
    HDU 4424 并查集+贪心思想
    POJ 1611 记录节点数的并查集
    HDU 4430 二分查找
  • 原文地址:https://www.cnblogs.com/chenjianhong/p/4145020.html
Copyright © 2011-2022 走看看