JS仿iGoogle自定义首页模块拖拽特效的方法


Posted in Javascript onFebruary 13, 2015

本文实例讲述了JS仿iGoogle自定义首页模块拖拽特效的方法。分享给大家供大家参考。具体实现方法如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>JS仿iGoogle自定义首页模块拖拽效果</title>

    <script type="text/javascript">

        var Common = {

            getEvent: function() {//ie/ff

                if (document.all) {

                    return window.event;

                }

                func = getEvent.caller;

                while (func != null) {

                    var arg0 = func.arguments[0];

                    if (arg0) {

                        if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {

                            return arg0;

                        }

                    }

                    func = func.caller;

                }

                return null;

            },

            getMousePos: function(ev) {

                if (!ev) {

                    ev = this.getEvent();

                }

                if (ev.pageX || ev.pageY) {

                    return {

                        x: ev.pageX,

                        y: ev.pageY

                    };

                }
                if (document.documentElement && document.documentElement.scrollTop) {

                    return {

                        x: ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft,

                        y: ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop

                    };

                }

                else if (document.body) {

                    return {

                        x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,

                        y: ev.clientY + document.body.scrollTop - document.body.clientTop

                    };

                }

            },

            getElementPos: function(el) {

                el = this.getItself(el);

                var _x = 0, _y = 0;

                do {

                    _x += el.offsetLeft;

                    _y += el.offsetTop;

                } while (el = el.offsetParent);

                return { x: _x, y: _y };

            },

            getItself: function(id) {

                return "string" == typeof id ? document.getElementById(id) : id;

            },

            getViewportSize: { w: (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : (document.body?document.body.offsetWidth:0), h: (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : (document.body ? document.body.offsetHeight : 0) },

            isIE: document.all ? true : false,

            setOuterHtml: function(obj, html) {

                var Objrange = document.createRange();

                obj.innerHTML = html;

                Objrange.selectNodeContents(obj);

                var frag = Objrange.extractContents();

                obj.parentNode.insertBefore(frag, obj);

                obj.parentNode.removeChild(obj);

            },

            firstChild: function(parentObj, tagName) {

                if (Common.isIE) {

                    return parentObj.firstChild;

                }

                else {

                    var arr = parentObj.getElementsByTagName(tagName);

                    return arr[0];

                }

            },

            lastChild: function(parentObj, tagName) {

                if (Common.isIE) {

                    return parentObj.lastChild;

                }

                else {

                    var arr = parentObj.getElementsByTagName(tagName);

                    return arr[arr.length - 1];

                }

            },

            setCookie: function(name, value) {

                document.cookie = name + "=" + value;

            },

            getCookie: function(name) {

                var strCookie = document.cookie;

                var arrCookie = strCookie.split("; ");

                for (var i = 0; i < arrCookie.length; i++) {

                    var arr = arrCookie[i].split("=");

                    if (!arr[1]) {

                        return "";

                    }

                    if (arr[0] == name) {

                        return arr[1];

                    }

                }

                return "";

            },

            delCookie: function(name) {

                var exp = new Date();

                exp.setTime(exp.getTime() - 1);

                var cval = this.getCookie(name);

                if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();

            }

        }

        var Class = {

            create: function() {

                return function() { this.init.apply(this, arguments); }

            }

        }

        var Drag = Class.create();

        Drag.prototype = {

            init: function(titleBar, dragDiv, Options) {

                //设置点击是否透明,默认透明60%

                titleBar = Common.getItself(titleBar);

                dragDiv = Common.getItself(dragDiv);

                this.dragArea = { maxLeft: -9999, maxRight: 9999, maxTop: -9999, maxBottom: 9999 };

                if (Options) {

                    this.opacity = Options.opacity ? (isNaN(parseInt(Options.opacity)) ? 100 : parseInt(Options.opacity)) : 100;

                    if (Options.area) {

                        if (Options.area.left && !isNaN(parseInt(Options.area.left))) { this.dragArea.maxLeft = Options.area.left };

                        if (Options.area.right && !isNaN(parseInt(Options.area.right))) { this.dragArea.maxRight = Options.area.right };

                        if (Options.area.top && !isNaN(parseInt(Options.area.top))) { this.dragArea.maxTop = Options.area.top };

                        if (Options.area.bottom && !isNaN(parseInt(Options.area.bottom))) { this.dragArea.maxBottom = Options.area.bottom };

                    }

                }

                else {

                    this.opacity = 60;

                }

                this.originDragDiv = null;

                this.tmpX = 0;

                this.tmpY = 0;

                this.moveable = false;

                this.dragArray = [];
                var dragObj = this;

                var dragTbl = document.getElementById("dragTable");
                titleBar.onmousedown = function(e) {

                    var ev = e || window.event || Common.getEvent();

                    //只允许通过鼠标左键进行拖拽,IE鼠标左键为1 FireFox为0

                    if (Common.isIE && ev.button == 1 || !Common.isIE && ev.button == 0) {

                    }

                    else {

                        return false;

                    }
                    //处理特殊情况:在最上/下面MOVE时不碰到现有DIV的情况下,又回到起始拖拽的列最上/下方

                    var tmpColId;

                    for (c = 0; c < dragTbl.rows[0].cells.length; c++) {

                        for (k = 0; k < dragTbl.rows[0].cells[c].getElementsByTagName("DIV").length; k++) {

                            if (dragDiv.id == dragTbl.rows[0].cells[c].getElementsByTagName("DIV")[k].id) {

                                tmpColId = c;

                                break;

                            }

                        }

                    }

                    var tmpPosFirstChild = Common.getElementPos(Common.firstChild(dragTbl.rows[0].cells[tmpColId], "DIV"));

                    var tmpPosLastChild = Common.getElementPos(Common.lastChild(dragTbl.rows[0].cells[tmpColId], "DIV"));

                    var tmpObj = { colId: tmpColId, firstChildUp: tmpPosFirstChild.y, lastChildDown: tmpPosLastChild.y + Common.lastChild(dragTbl.rows[0].cells[tmpColId], "DIV").offsetHeight };
                    //保存当前可拖拽各容器的所在位置

          dragObj.dragArray = dragObj.RegDragsPos();
                    //插入虚线框

                    var dashedElement = document.createElement("div");

                    dashedElement.style.cssText = dragDiv.style.cssText;

                    dashedElement.style.border = " dashed 2px #aaa ";

                    dashedElement.style.marginBottom = "6px";

                    dashedElement.style.width = dragDiv.offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px"; //减去boderWidth使虚线框大小保持与dragDiv一致

         dashedElement.style.height = dragDiv.offsetHeight - 2 * parseInt(dashedElement.style.borderWidth) + "px"; //加上px 保证FF正确                    

          dashedElement.style.position = "relative";

                    if (dragDiv.nextSibling) {

                        dragDiv.parentNode.insertBefore(dashedElement, dragDiv.nextSibling);

                    }

                    else {

                        dragDiv.parentNode.appendChild(dashedElement);

                    }

                    //拖动时变为absolute

                    dragDiv.style.width = dragDiv.offsetWidth + "px";

                    dragDiv.style.position = "absolute";


                    dragObj.moveable = true;

                    dragDiv.style.zIndex = dragObj.GetZindex() + 1;
                    var downPos = Common.getMousePos(ev);

                    dragObj.tmpX = downPos.x - dragDiv.offsetLeft;

                    dragObj.tmpY = downPos.y - dragDiv.offsetTop;
                    if (Common.isIE) {

                        dragDiv.setCapture();

                    } else {

                        window.captureEvents(Event.mousemove);

                    }
                    dragObj.SetOpacity(dragDiv, dragObj.opacity);
                    //FireFox 去除容器内拖拽图片问题

                    if (ev.preventDefault) {

                        ev.preventDefault();

                        ev.stopPropagation();

                    }
                    document.onmousemove = function(e) {

                        if (dragObj.moveable) {

                            var ev = e || window.event || Common.getEvent();

                            //IE 去除容器内拖拽图片问题

                            if (document.all) //IE

                            {

                                ev.returnValue = false;

                            }
                            var movePos = Common.getMousePos(ev);

                            dragDiv.style.left = Math.max(Math.min(movePos.x - dragObj.tmpX, dragObj.dragArea.maxRight), dragObj.dragArea.maxLeft) + "px";

                            dragDiv.style.top = Math.max(Math.min(movePos.y - dragObj.tmpY, dragObj.dragArea.maxBottom), dragObj.dragArea.maxTop) + "px";
                            var targetDiv = null;

                            for (var k = 0; k < dragObj.dragArray.length; k++) {

                                if (dragDiv == dragObj.dragArray[i]) {

                                    continue;

                                }
                                if (movePos.x > dragObj.dragArray[k].PosLeft && movePos.x < dragObj.dragArray[k].PosLeft + dragObj.dragArray[k].PosWidth

                                    && movePos.y > dragObj.dragArray[k].PosTop && movePos.y < dragObj.dragArray[k].PosTop + dragObj.dragArray[k].PosHeight

                                ) {

                                    targetDiv = document.getElementById(dragObj.dragArray[k].DragId);

                                    if (movePos.y < dragObj.dragArray[k].PosTop + dragObj.dragArray[k].PosHeight / 2) {

                                        //往上移

                                        dashedElement.style.width = targetDiv.offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";

                                        targetDiv.parentNode.insertBefore(dashedElement, targetDiv);

                                    }

                                    else {

                                        //往下移

                                        dashedElement.style.width = targetDiv.offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";

                                        if (targetDiv.nextSibling) {

                                            targetDiv.parentNode.insertBefore(dashedElement, targetDiv.nextSibling);

                                        }

                                        else {

                                            targetDiv.parentNode.appendChild(dashedElement);

                                        }

                                    }

                                }

                            }

                            

                            for (j = 0; j < dragTbl.rows[0].cells.length; j++) {

                                var startLeft = Common.getElementPos(dragTbl.rows[0].cells[j]).x;

                                if (movePos.x > startLeft && movePos.x < startLeft + dragTbl.rows[0].cells[j].offsetWidth) {

                                    ///列无DIV

                                    if (dragTbl.rows[0].cells[j].getElementsByTagName("div").length == 0) {

                                        dashedElement.style.width = dragTbl.rows[0].cells[j].offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";

                                        dragTbl.rows[0].cells[j].appendChild(dashedElement);

                                    }

                                    else {

                                        var posFirstChild = Common.getElementPos(Common.firstChild(dragTbl.rows[0].cells[j], "DIV"));

                                        var posLastChild = Common.getElementPos(Common.lastChild(dragTbl.rows[0].cells[j], "DIV"));

                                        //处理特殊情况:在最上/下面MOVE时不碰到现有DIV的情况下,又回到起始拖拽的列最上/下方

                                        var tmpUp, tmpDown;

                                        if (tmpObj.colId == j) {

                                            tmpUp = tmpObj.firstChildUp;

                                            tmpDown = tmpObj.lastChildDown;

                                        }

                                        else {

                                            tmpUp = posFirstChild.y;

                                            tmpDown = posLastChild.y + Common.lastChild(dragTbl.rows[0].cells[j], "DIV").offsetHeight;

                                        }
                                        if (movePos.y < tmpUp) {///从最上面插入虚线框

                                            dashedElement.style.width = Common.firstChild(dragTbl.rows[0].cells[j], "DIV").offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";

                                            dragTbl.rows[0].cells[j].insertBefore(dashedElement, Common.firstChild(dragTbl.rows[0].cells[j], "DIV"));

                                        }

                                        else if (movePos.y > tmpDown) {///从最下面插入虚线框

                                            dashedElement.style.width = Common.lastChild(dragTbl.rows[0].cells[j], "DIV").offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";

                                            dragTbl.rows[0].cells[j].appendChild(dashedElement);

                                        }
                                    }

                                }

                            }

                        }

                    };
                    document.onmouseup = function() {

                        if (dragObj.moveable) {

                            if (Common.isIE) {

                                dragDiv.releaseCapture();

                            }

                            else {

                                window.releaseEvents(dragDiv.mousemove);

                            }

                            dragObj.SetOpacity(dragDiv, 100);

                            dragObj.moveable = false;

                            dragObj.tmpX = 0;

                            dragObj.tmpY = 0;
                            //务必写在此IF内

                            dragDiv.style.left = "";

                            dragDiv.style.top = "";
                            dragDiv.style.width = "";

                            dragDiv.style.position = "";  

                            dashedElement.parentNode.insertBefore(dragDiv, dashedElement);

                            dashedElement.parentNode.removeChild(dashedElement);

                        }
                    };
                }

            },

            SetOpacity: function(dragDiv, n) {

                if (Common.isIE) {

                    dragDiv.filters.alpha.opacity = n;

                }

                else {

                    dragDiv.style.opacity = n / 100;

                }
            },

            GetZindex: function() {

                var maxZindex = 0;

                var divs = document.getElementsByTagName("div");

                for (z = 0; z < divs.length; z++) {

                    maxZindex = Math.max(maxZindex, divs[z].style.zIndex);

                }

                return maxZindex;

            },

            RegDragsPos: function() {

                var arrDragDivs = new Array();

                var dragTbl = document.getElementById("dragTable");

                var tmpDiv, tmpPos;

                for (i = 0; i < dragTbl.getElementsByTagName("div").length; i++) {

                    tmpDiv = dragTbl.getElementsByTagName("div")[i];

                    if (tmpDiv.className == "dragDiv") {

                        tmpPos = Common.getElementPos(tmpDiv);

                        arrDragDivs.push({ DragId: tmpDiv.id, PosLeft: tmpPos.x, PosTop: tmpPos.y, PosWidth: tmpDiv.offsetWidth, PosHeight: tmpDiv.offsetHeight });

                    }

                }

                return arrDragDivs;

            }

        }
        window.onload = function() {

            var dragTbl = document.getElementById("dragTable");

            if (Common.getCookie("configArr")) {

                var configArr = eval("(" + Common.getCookie("configArr") + ")");

                for (i = 0; i < dragTbl.rows[0].cells.length; i++) {

                    for (j = 0; j < configArr[i].length; j++) {

                        dragTbl.rows[0].cells[i].appendChild(document.getElementById(configArr[i][j]));

                    }

                }

            }

            new Drag("titleBar1", "dragDiv1");

            new Drag("titleBar2", "dragDiv2");

            new Drag("titleBar3", "dragDiv3");

            new Drag("titleBar4", "dragDiv4");

            new Drag("titleBar5", "dragDiv5");

        }
        window.onunload = function() {

            var dragTbl = document.getElementById("dragTable");

            var configArr = "";

            for (i = 0; i < dragTbl.rows[0].cells.length; i++) {

                var tmpStr = "";

                for (j = 0; j < dragTbl.rows[0].cells[i].getElementsByTagName("DIV").length; j++) {

                    tmpStr += (tmpStr == "" ? "" : ",") + "'" + dragTbl.rows[0].cells[i].getElementsByTagName("DIV")[j].id + "'";

                }

                configArr += (configArr == "" ? "" : ",") + "[" + tmpStr + "]";

            }

            //format like: [['dragDiv3','dragDiv5'],['dragDiv4','dragDiv1'],['dragDiv2']]

            Common.setCookie("configArr", "[" + configArr + "]");            

        }

    </script>

    <style type="text/css">

    .spanDiv{

    position:relative;

    width:5px;

    height:5px;

    }
    .dragDiv,.nodragDiv{

    position:relative;

    filter:alpha(opacity=100);

    opacity:1;

    margin-bottom:6px;

    background-color:#FFFFFF;

    }

    </style>

</head>

<body > 

<script type="text/javascript">
</script>   

    <table id="dragTable" cellpadding="3"  style=" border:solid 0px green;width:98%;">

        <tr>

            <td valign="top" style="width:30%">

                <div class="dragDiv" id="dragDiv1" >

                    <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">

                        <tr id="titleBar1"  style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">

                            <th align="left" unselectable="on" >Title1</th>

                        </tr>

                        <tr style="height:130px;padding:3px;" align="left" valign="top" >

                            <td unselectable="on">这里的字比较长....我来了....中国....中国...外国.,看一下有没有溢出></td> 

                        </tr>

                    </table>

                </div>               

                <div class="dragDiv" id="dragDiv2">

                    <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">

                        <tr id="titleBar2" style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">

                            <th align="left" unselectable="on" >Title2</th>

                        </tr>

                        <tr style="height:130px;padding:3px;" align="left" valign="top" >

                            <td unselectable="on">Content2...</td> 

                        </tr>

                    </table>

                </div>

            </td>

            <td valign="top" style="width:50%">

                <div class="dragDiv" id="dragDiv3">

                    <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">

                        <tr id="titleBar3" style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">

                            <th align="left" unselectable="on" >Title3</th>

                        </tr>

                        <tr style="height:230px;padding:3px;" align="left" valign="top" >

                            <td unselectable="on">Content3...</td> 

                        </tr>

                    </table>

                </div>                

            </td>

            <td valign="top" style="width:20%">

                <div class="dragDiv" id="dragDiv4">

                    <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">

                        <tr id="titleBar4" style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">

                            <th align="left" unselectable="on" >Title4</th>

                        </tr>

                        <tr style="height:130px;padding:3px;" align="left" valign="top" >

                            <td unselectable="on">Content4...</td> 

                        </tr>

                    </table>

                </div>

                <div class="dragDiv" id="dragDiv5">

                    <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">

                        <tr id="titleBar5" style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">

                            <th align="left" unselectable="on" >Title5</th>

                        </tr>

                        <tr style="height:130px;padding:3px;" align="left" valign="top" >

                            <td unselectable="on">Content5...</td> 

                        </tr>

                    </table>

                </div>

            </td>

        </tr>    

    </table>

</body>

</html>
<br><br><hr> 收集于互联网,只为兴趣与学习交流,不作商业用途。</font></p>

希望本文所述对大家的javascript程序设计有所帮助。

Javascript 相关文章推荐
javascript学习笔记(一)基础知识
Sep 30 Javascript
jQuery中siblings()方法用法实例
Jan 08 Javascript
jQuery实现鼠标经过像翻页和描点链接效果
Aug 08 Javascript
JS 获取HTML标签内的子节点的方法
Sep 21 Javascript
微信小程序 引入es6 promise
Apr 12 Javascript
JS实现二叉查找树的建立以及一些遍历方法实现
Apr 17 Javascript
vue router仿天猫底部导航栏功能
Oct 18 Javascript
ActiveX控件的使用-js实现打印超市小票功能代码详解
Nov 22 Javascript
javascript中join方法实例讲解
Feb 21 Javascript
Vue + Scss 动态切换主题颜色实现换肤的示例代码
Apr 27 Javascript
vue项目如何监听localStorage或sessionStorage的变化
Jan 04 Vue.js
vue穿梭框实现上下移动
Jan 29 Vue.js
JS弹出可拖拽可关闭的div层完整实例
Feb 13 #Javascript
AngularJS表单编辑提交功能实例
Feb 13 #Javascript
javascript转换日期字符串为Date日期对象的方法
Feb 13 #Javascript
jQuery动态修改超链接地址的方法
Feb 13 #Javascript
jQuery实现contains方法不区分大小写的方法
Feb 13 #Javascript
javascript获取元素离文档各边距离的方法
Feb 13 #Javascript
jQuery点缩略图弹出层显示大图片
Feb 13 #Javascript
You might like
德劲1103二次变频版的打磨
2021/03/02 无线电
ezSQL PHP数据库操作类库
2010/05/16 PHP
php中隐形字符65279(utf-8的BOM头)问题
2014/08/16 PHP
PHP获取音频文件的相关信息
2015/06/22 PHP
PHP内存使用情况如何获取
2015/10/10 PHP
php中类和对象:静态属性、静态方法
2017/04/09 PHP
PHP实现用session来实现记录用户登陆信息
2018/10/15 PHP
JavaScript学习历程和心得小结
2010/08/16 Javascript
express的中间件basicAuth详解
2014/12/04 Javascript
最全的Javascript编码规范(推荐)
2016/06/22 Javascript
功能强大的Bootstrap效果展示(二)
2016/08/03 Javascript
jquery二级目录选中当前页的css样式
2016/12/08 Javascript
js构建二叉树进行数值数组的去重与优化详解
2018/03/26 Javascript
JS在if中的强制类型转换方式
2018/07/15 Javascript
VUE 实现动态给对象增加属性,并触发视图更新操作示例
2019/11/29 Javascript
JQuery获得内容和属性方法解析
2020/05/30 jQuery
python编写网页爬虫脚本并实现APScheduler调度
2014/07/28 Python
解决Python pandas df 写入excel 出现的问题
2018/07/04 Python
python批量修改文件夹及其子文件夹下的文件内容
2019/03/15 Python
关于Python turtle库使用时坐标的确定方法
2020/03/19 Python
深入了解Python 方法之类方法 &amp; 静态方法
2020/08/17 Python
Python约瑟夫生者死者小游戏实例讲解
2021/01/04 Python
CSS3制作缩略图的详细过程
2016/07/08 HTML / CSS
美国顶级奢侈茶:Mighty Leaf Tea(美泰茶)
2016/11/26 全球购物
ALDO英国官网:加拿大女鞋品牌
2018/02/19 全球购物
公司会计岗位职责
2014/02/13 职场文书
房屋租赁意向书
2014/04/01 职场文书
我爱我校演讲稿
2014/05/21 职场文书
先进员工获奖感言
2014/08/14 职场文书
仲裁协议书
2014/09/26 职场文书
入党积极分子十八届四中全会思想汇报
2014/10/23 职场文书
2014年公务员个人工作总结
2014/11/22 职场文书
销售工作决心书
2015/02/04 职场文书
国家助学金受助感言
2015/08/01 职场文书
家长对孩子的寒假评语
2015/10/09 职场文书
2015年中学体育教师工作总结
2015/10/23 职场文书