码迷,mamicode.com
首页 > 编程语言 > 详细

[javascript]一种兼容性比较好的简单拖拽

时间:2015-07-17 00:19:19      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

作为一个马上要找工作、非计算机专业、热爱前端的大四狗,最近开始疯狂写demo、看书,准备九、十月份的校招。

晚上用js实现了一个比较简单(low)的拖拽效果,初步测试兼容性还是不错的,于是写一段小博文记录下~大神求轻喷

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        window.onload = function (){
            var disX = 0;
            var disY = 0;
            var oBox = document.getElementById("box");
            oBox.onmousedown = function (ev){
                var oEvent = ev || event;

                oBox.style.cursor = "move";
                disX = oEvent.clientX - oBox.offsetLeft;
                disY = oEvent.clientY - oBox.offsetTop;

                document.onmousemove = function (ev){
                    var oEvent = ev || event;
                    var theLeft = oEvent.clientX - disX;
                    var theTop = oEvent.clientY - disY;
                    
                    // 禁止用户从浏览器左框拖出
                    if (theLeft < 0) {
                        theLeft = 0;
                    } else if (theLeft > document.documentElement.clientWidth-
                        oBox.offsetWidth) {
                        theLeft = document.documentElement.clientWidth-
                        oBox.offsetWidth;
                    } else if (theTop < 0) {
                        theTop = 0;
                    } else if (theTop > document.documentElement.clientHeight-
                        oBox.offsetHeight) {
                        theTop = document.documentElement.clientHeight-
                        oBox.offsetHeight;
                    }
                    oBox.style.left = theLeft + ‘px‘;
                    oBox.style.top = theTop + ‘px‘;
                }

            }

            document.onmouseup = function (){
                document.onmousemove =null;
            }
         // 窗口重设大小时的处理方法
            window.onresize = function (){
                oBox.style.left = document.documentElement.clientWidth/2-oBox.offsetWidth/2 + ‘px‘;
                oBox.style.top = document.documentElement.clientHeight/2-oBox.offsetHeight/2 + ‘px‘;
            }
            // 兼容firefox 3.6.19
            return false;
        }
    </script>
</body>
</html>

 

[javascript]一种兼容性比较好的简单拖拽

标签:

原文地址:http://www.cnblogs.com/zhongshanblog/p/4652785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!