码迷,mamicode.com
首页 > 其他好文 > 详细

拖拽效果

时间:2016-10-08 20:08:21      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>拖拽效果</title>
</head>
<style>
    body {
        background: skyblue;
    }
    #wrap {
        margin: 50px auto;
        width: 400px;
        height: 400px;
        border: 8px #b1b8e0 solid;
        background: #e9eff8;
        position: relative;
    }
    #drag {
        width: 50px;
        height: 50px;
        border: 8px #eb651d;
        background: #9de4ec;
        position: absolute;
        top: 0;
        left: 0;
    }
</style>
<body>
    <div id="wrap">
        <div id="drag"></div>
    </div>
    <!-- ================================================================================================================================= -->
    <script>
        var wrap = document.getElementById(wrap);
        var drag = document.getElementById(drag);

        drag.onmousedown = function(event){
            var event = event || window.event;//后者为IE
            //clientX获取鼠标距左窗口的距离
            //offsetLeft待移动对象的左外边距
            //tmpX作用在待移动对象上的鼠标到待移动对象左边距的距离
            var tmpX = event.clientX - drag.offsetLeft;
            var tmpY = event.clientY - drag.offsetTop;
            //取消默认行为
            if(event.preventDefault){
                event.preventDefault();
            }else{
                event.returnValue = false;
            }
            document.onmousemove = function(event){
                var event = event || window.event;
                //endX移动后对象的左边到左窗口的距离
                //clientWidth = width + padding
                //offsetWidth = width + padding + border
                //简单的说mouseX = 大框的宽度 -(小框的宽度+内外边距)
                var endX = event.clientX - tmpX;
                var endY = event.clientY - tmpY;
                var mouseX = wrap.clientWidth - drag.offsetWidth;
                var mouseY = wrap.clientHeight - drag.offsetHeight;

                if(endX >= mouseX){
                    endX = mouseX;
                }
                if(endX <= 0){
                    endX = 0;
                }
                if(endY >= mouseY){
                    endY = mouseY;
                }
                if(endY <= 0){
                    endY = 0;
                }
                drag.style.left = endX + px;
                drag.style.top = endY + px;
            }

        }
        //鼠标抬起时清空移动操作
        document.onmouseup = function(){
            document.onmousemove = null;
        }
    </script>
</body>
</html>

 

效果图:

技术分享

拖拽效果

标签:

原文地址:http://www.cnblogs.com/kewenxin/p/5939643.html

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