js基础_74、拖拽练习

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #box1{
                width: 150px;
                height: 150px;
                background-color: aqua;
                position: absolute;
            }
            #box2{
                width: 150px;
                height: 150px;
                top: 300px;
                left: 300px;
                background-color: yellow;
                position: absolute;
            }
        </style>
        <script>
            window.onload=function(){
                var box1=document.getElementById("box1");
                var box2=document.getElementById("box2");
                bind(box1);
                bind(box2);
            };
            var bind=function(obj){
                //给box1元素绑定鼠标按下事件
                obj.onmousedown=function(event){
                    //div的偏移量   鼠标.clientX-元素.offsetleft,为了提升体验,
                    //将元素拖拽中,鼠标焦点一直固定在元素的某个用户点击的位置,而不是总是固定在左上角
                    //div的偏移量   鼠标.clientY-元素.offsetTop
                    event=event||window.event;
                    var ox=event.clientX-obj.offsetLeft;
                    var oy=event.clientY-obj.offsetTop;
                    //给文档绑定鼠标移动事件,因为要获取鼠标在文档中的坐标,而不是box1这个元素的坐标
                    document.onmousemove=function(event){
                        event=event||window.event;
                        //移动元素box1
                        var x=event.clientX-ox;
                        var y=event.clientY-oy;
                        obj.style.left=x+"px";
                        obj.style.top=y+"px";
                    };
                    //鼠标松开事件
                    document.onmouseup=function(){
                        //取消document.onmousemove移动事件
                        document.onmousemove=null;
                        //取消document.onmouseup鼠标松开事件
                        document.onmouseup=null;
                        /*
                         *当我们拖拽一个网页中的内容时,浏览器会默认去搜索内容。
                         * 此时会导致拖拽功能的异常,这个是浏览器提供的默认行为,
                         * 如果不希望发生这个行为,则可以通过return false来取消默认行为
                         * 但是这样对IE8不起作用
                         * 
                         * */
                    };
                    return false;
                };
            }
        </script>
    </head>
    <body id="body">
        hello
        <div id="box1"></div>
        <div id="box2"></div>
    </body>
</html>
posted @   青仙  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示