zoukankan      html  css  js  c++  java
  • 解决拖拽有内容的div的bug和兼容问题

    <!DOCTYPE html>

    <html>

     

    <head>

    <meta charset="UTF-8">

    <title></title>

    <style type="text/css">

    #big {

    height: 800px;

    width: 800px;

    background-color: #008000;

    position: relative;

    }

     

    #small {

    height: 100px;

    width: 100px;

    background-color: orangered;

    position: absolute;

    }

    </style>

    </head>

     

    <body>

    <div id="big">

    拖拽有内容的div,在浏览器上都会有bug 解决FF和chrome上的bug只需要加上return false就可以了 解决低版本IE上的bug就需要用到事件捕获setCapture和释放捕获releaseCapture() 为了解决兼容问题就需要做一个判断,需要两套代码

    <div id="small">

    解决FF和chrome上的bug只需要加上return false就可以了

     

    </div>

    </div>

    </body>

    <script type="text/javascript">

    //拖拽有内容的div,在浏览器上都会有bug

    //解决FF和chrome上的bug只需要加上return false就可以了

    //解决低版本IE上的bug就需要用到事件捕获setCapture和释放捕获releaseCapture()

    //为了解决兼容问题就需要做一个判断,需要两套代码

    var big = document.getElementById("big");

    var small = document.getElementById("small");

    //鼠标按下的函数

    var x = 0;

    var y = 0;

    small.onmousedown = function(ev) {

    var oEvent = ev || event;

    x = oEvent.clientX - small.offsetLeft;

    y = oEvent.clientY - small.offsetTop;

     

    if(small.setCapture) { //在IE下

    //鼠标移动的函数

    small.onmousemove = mouseMove;

    //鼠标抬起的函数

    small.onmouseup = mouseUp;

    //解决IE下有内容的拖拽情况下的bug

    //用到捕获

    small.setCapture();

     

    } else { //在火狐下

    //鼠标移动的函数

    document.onmousemove = mouseMove;

    //鼠标抬起的函数

    document.onmouseup = mouseUp;

     

    //return false可以解决有内容的拖拽情况下的bug

    //但是对IE不适用

    return false;

     

    }

     

    }

     

    //定义一个鼠标移动的函数

    function mouseMove(ev) {

    var oEvent = ev || event;

     

    var L = oEvent.clientX - x;

    var T = oEvent.clientY - y;

    //保证small不被拖出大框,并且实现磁性吸附的效果

    if(L < 100) {

    L = 0;

    } else if(L > big.offsetWidth - small.offsetWidth) {

    L = big.offsetWidth - small.offsetWidth;

    }

    if(T < 100) {

    T = 0;

    } else if(T > big.offsetHeight - small.offsetHeight) {

    T = big.offsetHeight - small.offsetHeight;

    }

    small.style.left = L + "px";

    small.style.top = T + "px";

     

    }

    //定义一个鼠标抬起的函数

    function mouseUp(ev) {

    this.onmousemove = null;

    this.onmouseup = null;

    //释放捕获,只在IE下适用,所以要做一个判断

    if(this.releaseCapture) {

    this.releaseCapture();

    }

     

    }

    </script>

     

    </html>

  • 相关阅读:
    Java类变量和成员变量初始化过程
    Linux命令学习笔记
    gitlab本地部署方法(ubuntu16.04+gitlab9.5.5)
    Hanoi塔
    求递归算法时间复杂度:递归树
    最大堆/最小堆
    Matlab中plot基本用法
    这是一篇叼炸天的博客
    c++ static理解
    经典排序算法+文件操作~c语言实现
  • 原文地址:https://www.cnblogs.com/niuniudashijie/p/6128705.html
Copyright © 2011-2022 走看看